Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@unleash/nextjs

Package Overview
Dependencies
Maintainers
5
Versions
34
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@unleash/nextjs

Unleash SDK for Next.js

  • 0.0.5
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
31K
decreased by-24.13%
Maintainers
5
Weekly downloads
 
Created
Source

🏗️ Early version

We need your feedback. Share your comments in 🗣️ GitHub Discussions or on Unleash community 💬 Slack server.

Unleash Next.js SDK

This package allows easy integration of Unleash feature flags in a Next.js application.

Setup

Installation

To install, simply run:

npm install @unleash/nextjs
# or
yarn add @unleash/nextjs
# or
pnpm add @unleash/nextjs

Environment variables

This package will attempt to load configuration from Next.js Environment variables.

PrefixableVariableDefaultUsed in
NEXT_PUBLIC_UNLEASH_BASE_URLhttp://localhost:4242/apiFlagProvider, getFrontendFlags
NoUNLEASH_API_TOKENdefault:development.unleash-insecure-api-tokengetDefinitions
NEXT_PUBLIC_UNLEASH_FRONTEND_API_TOKENdefault:development.unleash-insecure-frontend-api-tokenFlagProvider, getFrontendFlags
NEXT_PUBLIC_UNLEASH_APP_NAMEnextjsFlagProvider, getFrontendFlags, getDefinitions

If you plan to use configuration in the browser, add NEXT_PUBLIC_ prefix. If both are defined and available, private variable takes priority. You can use both to have different values on client-side and server-side.


Usage

A). Client-side only - simple use case and for development purposes (CSR)

Fastest way to get started is to connect frontend directly to Unleash. You can find out more about direct Front-end API access in our documentation, including a guide on how to setup a client-side SDK key.

import type { AppProps } from "next/app";
import { FlagProvider } from "@unleash/nextjs";

export default function App({ Component, pageProps }: AppProps) {
  return (
    <FlagProvider
      // config prop is optional if environment variables are set
      config={{
        url: "http://localhost:4242/api", // this will override NEXT_PUBLIC_UNLEASH_BASE_URL
        clientKey: "<Frontend_API_token>", // NEXT_PUBLIC_UNLEASH_FRONTEND_API_TOKEN
        appName: "nextjs", // NEXT_PUBLIC_UNLEASH_APP_NAME
        refreshInterval: 15, // additional client configuration
      }}
    >
      <Component {...pageProps} />
    </FlagProvider>
  );
}

With <FlagProvider /> in place you can now use hooks like: useFlag, useVariant, or useFlagsStatus to block rendering until flags are ready.

import { useFlag } from "@unleash/nextjs";

const YourComponent = () => {
  const isEnabled = useFlag("nextjs-poc");

  return <>{isEnabled ? "ENABLED" : "DISABLED"}</>;
};

If you only plan to use Unleash client-side React SDK now also works with Next.js. Check documentation there for more examples.


B). Static Site Generation, optimized performance (SSG)

With same access as in the client-side example above you can resolve Unleash feature flags when building static pages.

Use getFrontendFlags to load

import { flagsClient, getFrontendFlags, type IVariant } from "@unleash/nextjs";
import type { GetStaticProps, NextPage } from "next";

type Data = {
  isEnabled: boolean;
  variant: IVariant;
};

const ExamplePage: NextPage<Data> = ({ isEnabled, variant }) => (
  <>
    Flag status: {isEnabled ? "ENABLED" : "DISABLED"}
    <br />
    Variant: {variant.name}
  </>
);

export const getStaticProps: GetStaticProps<Data> = async (_ctx) => {
  /* Using server-side SDK: */
  const definitions = await getDefinitions();
  const { toggles } = evaluateFlags(definitions);

  /* Or with Proxy/Frontend API */
  // const { toggles } = await getFrontendFlags();

  const flags = flagsClient(toggles);

  return {
    props: {
      isEnabled: flags.isEnabled("nextjs-poc"),
      variant: flags.getVariant("nextjs-poc"),
    },
  };
};

export default ExamplePage;

The same approach will work for ISR (Incremental Static Regeneration).


C). Server Side Rendering (SSR)

import {
  flagsClient,
  evaluateFlags,
  getDefinitions,
  type IVariant,
} from "@unleash/nextjs";
import type { GetServerSideProps, NextPage } from "next";

type Data = {
  isEnabled: boolean;
};

const ExamplePage: NextPage<Data> = ({ isEnabled }) => (
  <>Flag status: {isEnabled ? "ENABLED" : "DISABLED"}</>
);

export const getServerSideProps: GetServerSideProps<Data> = async (ctx) => {
  const sessionId =
    ctx.req.cookies["unleash-session-id"] ||
    `${Math.floor(Math.random() * 1_000_000_000)}`;
  ctx.res.setHeader("set-cookie", `unleash-session-id=${sessionId}; path=/;`);

  const context = {
    sessionId, // needed for stickiness
    // userId: "123" // etc
  };

  const { toggles } = await getFrontendFlags(); // Use Proxy/Frontend API
  const flags = flagsClient(toggles);

  return {
    props: {
      isEnabled: flags.isEnabled("nextjs-poc"),
    },
  };
};

export default ExamplePage;

D). Bootstrapping / rehydration

You can bootstrap Unleash React SDK to have values loaded from the start. Initial value can be customized server-side.

import App, { AppContext, type AppProps } from "next/app";
import {
  FlagProvider,
  getFrontendFlags,
  type IMutableContext,
  type IToggle,
} from "@unleash/nextjs";

type Data = {
  toggles: IToggle[];
  context: IMutableContext;
};

export default function CustomApp({
  Component,
  pageProps,
  toggles,
  context,
}: AppProps & Data) {
  return (
    <FlagProvider
      config={{
        bootstrap: toggles,
        context,
      }}
    >
      <Component {...pageProps} />
    </FlagProvider>
  );
}

CustomApp.getInitialProps = async (ctx: AppContext) => {
  const context = {
    userId: "123",
  };

  const { toggles } = await getFrontendFlags(); // use Unleash Proxy

  return {
    ...(await App.getInitialProps(ctx)),
    bootstrap: toggles,
    context, // pass context along so client can refetch correct values
  };
};

What's next

Experimental features support

Unleash Next.js SDK can run on Edge Runtime and in Middleware. We are also interested in providing an example with App Directory.

Known limitation

  • In current interation server-side SDK does not support metrics.
  • Server-side SDK does not support "Hostname" strategy. Use custom context field and constraints instead.

FAQs

Package last updated on 20 Jan 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc