• Home
  • Integrations
  • SDKs
  • Guides
  • API docs
No results for ""
EXPAND ALL

EDIT ON GITHUB

Using LaunchDarkly with Next.js

Read time: 14 minutes
Last edited: Nov 19, 2021

Overview

This guide explains how to connect LaunchDarkly with Next.js on both the client and server side.

Next.js is a React-based framework for full-stack JavaScript development. One of the most powerful aspects of Next.js is that it offers tools that let you render content at multiple junctures: at build time; on the server; or on the client. It even offers an option for deferred rendering that builds pages only when they are first requested.

While these options add a lot of power, they can also create some confusion if you want to integrate Next.js and LaunchDarkly. Which library do you need? Where do you import and configure it? How do you use it once it is set up?

In this tutorial, we'll answer these questions for the different types of integrations Next.js offers.

Rendering options in Next.js

In the past, rendering occurred in just one place: the server. In response to a page request, the server would return HTML that a browser could render. Things become more complicated when you use a "full stack" framework like Next.js, which is sometimes referred to as an isomorphic JavaScript framework. This framework doesn't only render content on the client with JavaScript (in this case, the client is a browser). It also renders on the backend using JavaScript within Node.js.

There are four different strategies for rendering content in a Next.js application. Keep in mind that an application could have any mix of any or all of these and, in some cases, even a single page may include multiple rendering strategies for different parts of the page.

The four strategies are:

  • Pre-rendering (static site rendering, static site generation, or SSG): This content is rendered at build time before the application is deployed. This usually happens as part of a CI/CD build process. For example, new code checked into your git repository triggers a build in Netlify or Vercel, two popular deployment options for Next.js sites. A build hook or deploy hook can also trigger a new build. A common example is when you're using an external headless content management system so that changes to content are automatically re-rendered in the build.
  • Server-side rendering (SSR): This is the traditional style of rendering a page. The content is generated on the server (Node.js in this case) for every single request and then sent to the browser for the initial page load.
  • Client-side rendering: Some content, such as user-specific data on a pre-rendered page, cannot be fully rendered before deployment. In these cases, you must use JavaScript to modify the rendered output in the browser. Similarly, you may not want to re-render the page server-side for every interaction. In these cases, you'd also update the page using client-side JavaScript.
  • Deferred rendering: This is functionally equivalent to pre-rendering except that the requested page isn't rendered during the initial build. Instead, it's rendered only when the first user requests it. For example, pre-rendering an e-commerce site with thousands of product pages could cause excessively long builds for little value, because many of those pages may get minimal traffic. Instead, you can defer rendering these pages until they are first requested. While the initial visitor may see a slight delay in loading the page, subsequent visitors will receive the page from the build cache.

Each of these types of rendering has different implications when you're working with a LaunchDarkly SDK.

There are two types of deferred rendering

There are two forms of deferred rendering: Incremental Static Regeneration (ISR) and Distributed Persistent Rendering (DPR). The key difference is that ISR can include a timeout, meaning that the generated page will go stale and re-render after a specified period. Whereas with DPR, the rendered page becomes part of the build and the only way to re-render it is with a new build.

Which SDK do I use?

LaunchDarkly offers multiple JavaScript SDKs that may be relevant to a Next.js project:

So, which one should you use? That depends on the flag you are integrating and the types of rendering it is affected by.

Consider these factors:

  • For pre-rendering, server-side rendering, and deferred rendering, use the server-side Node.js SDK. Although each of the rendering types are very different, they all happen on the server in one manner or another, even if that server is a build server generating static pages.
  • For client-side rendering, use the React SDK. Next.js is a React meta-framework, meaning that it is a framework built on top of React. One of the benefits is that the React SDK offers us the React hooks integration that is available in Next.js.

In many cases, a Next.js application needs both the server-side Node.js SDK and the React SDK to use flags on both the frontend and backend.

Considering build impact

In some cases, flipping a flag has immediate impact, but in others it may require a site rebuild before a change appears. Let's explore the different rendering options, when you'll need to trigger a rebuild, and how to do that.

First, when do you need a rebuild? You'll need to trigger a rebuild for:

  • Pre-rendered pages: If your flag impacts the content or functionality on any pre-rendered page, the changes it has won't be visible until a rebuild triggers and deploys.
  • Deferred rendered pages: If a page's rendering is deferred using DPR or ISR, you must trigger a full rebuild, because you do not have an easy way to determine if the impacted pages have been built and already exist in the cache. The only way to ensure that the page updates appropriately is to do a full site rebuild. A page that uses ISR can have a cache timeout and rebuild to reflect any changes after the timeout expires, but this still requires waiting for that page's cache to be invalidated and then rebuilt for the next user's request. It's better and safer to initiate a full rebuild and confirm your changes appear.

Server-side rendered pages will reflect any changes on the next request. If a user is already on the page, they must refresh it to see the impact of a flag change. Client-side rendered pages will immediately reflect any changes in the browser without any refresh.

Automating rebuilds

You do not need to manually trigger a rebuild each time you make a flag change. Instead, you can use build hooks on your deployment platform to automate the process (for example, here's Netlify's build hook documentation or Vercel's deploy hook documentation) with a combination of tags and webhooks on LaunchDarkly.

First, you must add a tag. You can add this when you create a new feature flag that will need to trigger a rebuild. For example, you can name the tag build-impact. You can name yours whatever you like but it's best to keep it descriptive and consistent. Use the same tag for all flags that need to trigger a rebuild.

Adding a tag to a feature flag
Adding a tag to a feature flag

You add the tag so that you can use it to filter only those flags that require a full site rebuild to trigger the webhook. This means that if a tag is only used in SSR or client-side rendering, it won't cause a rebuild. This prevents needless deploys and saves you money, because most deployment platforms ultimately charge for build minutes.

Next, you must connect your tagged flag so it triggers a rebuild. The following examples show how to connect LaunchDarkly to Netlify's build hooks and Vercel's deploy hooks, but most deployment platforms offer a similar type of feature.

Creating a build hook on Netlify

In the Netlify admin dashboard:

  1. Click on the site you would like to connect the webhook to.

  2. Navigate to Site Settings > Build & Deploy > Build Hooks.

  3. Click the button to add a new build hook and give it a name (for example, "LaunchDarkly").

  4. Choose the git branch that will be used as the source when this build hook is called.

    Netlify allows branch deploys. You could use this to let flags from your test environment within LaunchDarkly trigger a deploy on a test branch in Netlify. For this example you can just choose the main branch, which typically deploys the public site.

Adding a build hook in Netlify
Adding a build hook in Netlify

  1. After you add the hook, a URL for the new hook appears. Copy the URL and save it.

Creating a deploy hook in Vercel

In the Vercel admin dashboard:

  1. Click on the site you would like to connect the webhook to.

  2. Navigate to Settings > Git > Deploy Hooks.

  3. Give the deploy hook a human-readable name and specify the git branch to use.

    Adding a deploy hook in Vercel
    Adding a deploy hook in Vercel

  4. Click Create Hook. After the deploy hook is created, copy the URL. You will need it to connect the deploy hook to LaunchDarkly.

Adding the build/deploy hook in LaunchDarkly

This procedure requires a build hook from Netlify or a deploy hook from Vercel. You can use either type of hook interchangeably in this procedure.

  1. In LaunchDarkly, navigate to Integrations and go to the "Webhooks" section.
  2. Click + Integration to add a new webhook.

Finding the webhook integration
Finding the webhook integration

  1. Give your webhook a human-readable name, and then paste the URL of the build/deploy hook you just created in Netlify or Vercel.

Adding a new webhook
Adding a new webhook

Next, you must add a policy to this webhook. The policy determines the permissions that the webhook has. This will ultimately limit the access it has to events triggered by changes to your LaunchDarkly flags and settings. This means the webhook will only call the build hook on those events it has access to. In this case, you only want it to respond to flags that are tagged build-impact.

To add a policy to the webhook:

  1. Navigate to the "Policy" section of the webhook and click Advanced editor. This lets us create a policy with very specific restrictions. The example code below says that this webhook has access to the environments (env/*) and flags (flag/*) tagged with build-impact.

  2. Paste this code into the advanced editor. Change the project key from brian-test to your LaunchDarkly project key. You can get the project key in the LaunchDarkly dashboard under Account settings > Projects.

Here is the code to paste and modify:

1[
2 {
3 "resources": [
4 "proj/brian-test:env/*:flag/*;build-impact"
5 ],
6 "actions": [
7 "*"
8 ],
9 "effect": "allow"
10 }
11]
  1. Click Save changes.

To test this policy, create a flag and tag it with build-impact. Now change its value and then go to your Netlify or Vercel dashboard. You should see a new build starting. Next, create a flag and do not tag it. Change its value and check your Netlify or Vercel dashboard. Nothing will change.

Integrating LaunchDarkly's SDKs into Next.js

Here are some examples of how to integrate the LaunchDarkly SDKs into Next.js applications. These examples show how to add flags into each of the different types of rendering scenarios: SSG, SSR, client-side rendering and ISR/DPR (also known as deferred rendering).

The code shown in these examples is available on GitHub. You can also see the project running on Netlify and Vercel. The application uses the DEV API to populate some content.

Creating a server-side component

First, you can create a helper component for any of the server-side rendering methods. Keep in mind that the server-side rendering methods include more than just SSR. Static rendering and deferred rendering both occur on the "server" in that their code runs on the backend. The key difference is that they render their pages as static files only once, and SSR renders the page on each request.

You can use this component for:

  • Static rendering
  • Server-side rendering
  • Deferred rendering

This component handles the initialization and configuration for the Node.js server-side SDK so you don't need to do this on every page that uses a LaunchDarkly flag. This component appears in the project as /lib/ld-server.js, but you can place it anywhere and name it whatever you like.

The component has two methods:

  • The initialize() method passes an API key to the SDK and then waits for the initialization process to be completed.
  • The getClient() method checks to see if the launchDarklyClient has been initialized and returns it if it has or calls the initialize() method if it hasn't.

Any page that uses this component only needs the getClient() method, which always returns an initialized LaunchDarkly SDK client.

Here is an example method:

1import LaunchDarkly from "launchdarkly-node-server-sdk";
2
3let launchDarklyClient;
4
5async function initialize() {
6 const client = LaunchDarkly.init(process.env.LAUNCHDARKLY_SDK_KEY);
7 await client.waitForInitialization();
8 return client;
9}
10
11export async function getClient() {
12 if (launchDarklyClient) return launchDarklyClient;
13 return (launchDarklyClient = await initialize());
14}

You must have a LAUNCHDARKLY_SDK_KEY environment variable set in a .env.local file. In addition, you must ensure that wherever you deploy this application, that environment variable is set as well.

For example, if you are deploying to Netlify:

  1. Within the site's settings on the dashboard, go to Build & Deploy > Environment.
  2. Click Edit Variables.
  3. Click Add Variable.
  4. Add the LAUNCHDARKLY_SDK_KEY variable.

Alternatively, if you are deploying to Vercel:

  1. Open the site in Vercel's dashboard and go to Settings > Environment Variables.
  2. Give the variable a name and value and then choose the environments that you would like it to apply to.
  3. Click Add. This saves the environment variable.

To get your LaunchDarkly SDK key, go to Account Settings > Projects. Choose your project and then copy the SDK key for the environment you wish to work with.

Static rendering (SSG)

Here are some use cases involving pre-rendered content. In Next.js, data being passed to a pre-rendered (also known as static) page is passed by the getStaticProps() function. If your page uses dynamic routes, you'll also need to define a getStaticPaths() method that outputs the paths that will be rendered. The integration of LaunchDarkly in both methods is the same.

The following example uses the ld-server.js component's getClient() method to get the initialized LaunchDarkly client. Then it requests the value of the featured-username key. This is a string key that is used to determine the DEV username to use to load posts from the DEV API. You could also have gotten a true / false flag and passed that value when rendering the UI to determine if a feature should be shown.

1export async function getStaticProps() {
2 const client = await getClient();
3 let featuredUsername = await client.variation(
4 "featured-username",
5 { key: "brian@launchdarkly.com" },
6 false
7 );
8 const response = await fetch(
9 `https://dev.to/api/articles?username=${featuredUsername}&page=1&per_page=10`
10 );
11 const data = await response.json();
12 return {
13 props: {
14 featuredUsername: featuredUsername,
15 posts: data,
16 },
17 };
18}

You could use a flag like this to modify the behavior of a page without needing to ask for code changes from the dev team.

In statically pre-rendered pages, you cannot use different variations for different users or roll out a variation. Every user sees the same statically rendered content. This is why you use a single constant value for the user. In this case, you can just use an email as the constant.

In the next example, you are loading two flags: show-about-us and new-about-us.

The show-about-us flag relates to the client-side rendering example that comes later. The new-about-us flag determines which file-based content (in this case a Markdown file) should be loaded and rendered.

Imagine a scenario where you wanted to give marketing the ability to launch an updated About Us page when new branding and messaging are ready to align with their campaigns. This flag allows you to do this even when the content is loaded from files in the git repository, such as if they were managed by a git-based headless CMS.

1export async function getStaticProps() {
2 const client = await getClient();
3 let showPage = await client.variation(
4 "show-about-us",
5 { key: "brian@launchdarkly.com" },
6 false
7 );
8 let loadPage = "";
9 let frontMatter = "";
10 let markdownBody = "";
11 if (showPage) {
12 let loadPage = await client.variation(
13 "new-about-us",
14 { key: "brian@launchdarkly.com" },
15 false
16 );
17 const content = await import(`../content/${loadPage}.md`);
18 const data = matter(content.default);
19 frontMatter = data.data;
20 markdownBody = data.content;
21 }
22 return {
23 props: {
24 frontmatter: frontMatter,
25 markdownBody: markdownBody,
26 showPage: showPage,
27 },
28 };
29}

In both these cases, you must trigger a rebuild before the content will update on the deployed site. Any of the flags references in either getStaticProps() or getStaticPaths() must have the build-impact tag you created earlier in order to automatically trigger a rebuild when the flag changes.

Server-side rendering (SSR)

Using a flag in a server-rendered page is very similar to a statically rendered page. You still get the client from the ld-server.js component and load the key from the SDK using the same syntax.

The key differences are:

  • You load the client and pull the value of the flag within the getServerSideProps() method, which is the functional equivalent of getStaticProps() but for SSR pages.
  • You don't need to trigger a rebuild when a flag changes. However, you need to refresh the page in order to see the content change.

In this example, you are also calling a string flag that determines which post category will be featured. The value of this flag determines the parameter you pass to the DEV API.

1export async function getServerSideProps() {
2 const client = await getClient();
3 let featuredCategory = await client.variation(
4 "featured-category",
5 { key: "brian@launchdarkly.com" },
6 false
7 );
8
9 const response = await fetch(
10 `https://dev.to/api/articles?tag=${featuredCategory}&page=1&per_page=5`
11 );
12 const data = await response.json();
13 return {
14 props: {
15 featuredCategory: featuredCategory,
16 posts: data,
17 },
18 };
19}

Client-side rendering

Client-side rendering is the only scenario in this guide that requires the React SDK. This means that it works differently than the previous examples.

The client-side SDK uses a different, more restricted key than the server-side SDKs. To get the SDK key, go to Account Settings > Projects. Copy the key and add a LAUNCHDARKLY_SDK_CLIENT value to .env.local. You also must ensure this key exists on your deployment provider as well.

Environment variables are not automatically made available to the client in Next.js. In order to do that, you must alter the next.config.js file in your project to add the code below to the module.exports block. This code essentially says to make the LAUNCHDARKLY_SDK_CLIENT variable available on the client using the same variable name.

Add this code to the module.exports block:

1env: {
2 LAUNCHDARKLY_SDK_CLIENT: process.env.LAUNCHDARKLY_SDK_CLIENT,
3},

There are two ways to initialize the React SDK so that it is available throughout your application. To learn more, read the React documentation. The following examples uses the withLDProvider method. To do this, you must have an _app.js in the root of your /pages directory, if one does not yet exist.

Rather than export default the MyApp function, wrap the application in a LaunchDarkly provider and return that.

Here is an example _app.js:

1import "../styles/globals.css";
2import { withLDProvider } from "launchdarkly-react-client-sdk";
3
4function MyApp({ Component, pageProps }) {
5 return <Component {...pageProps} />;
6}
7
8export default withLDProvider({
9 clientSideID: process.env.LAUNCHDARKLY_SDK_CLIENT,
10})(MyApp);

Now you can use your flags on the client. You can do this with the useFlags() React hook. The following example pulls a flag, show-about-us, and uses that to determine if the "About Us" link should be displayed within the site navigation. Because show-about-us is not a valid JavaScript variable name, LaunchDarkly automatically converts it to camel case.

Here is an example:

1import { useFlags } from "launchdarkly-react-client-sdk";
2import Link from "next/link";
3
4export default function Nav() {
5 let { showAboutUs } = useFlags();
6 return (
7 <div className="nav">
8 <ul>
9 <li>
10 <Link href="/">Home</Link>
11 </li>
12 <li>
13 <Link href="/ssr">SSR</Link>
14 </li>
15 {showAboutUs && (
16 <li className="about">
17 <Link href="/about">About Us</Link>
18 </li>
19 )}
20 </ul>
21 </div>
22 );
23}

Because this is running on the client, any flag changes you make in LaunchDarkly appear in the UI almost immediately, without requiring a page refresh.

For this particular example, there's a complication: we've removed the link to the About Us page from the UI, but the route for /about is still generated. This means that, if someone knew or figured out the path, they could still access the page. What if it was critical that this page not be accessible when show-about-us returns false?

You can make a few small changes to the /pages/about.js file. First, load the value within the page's getStaticProps() method.

Here's how:

1let showPage = await client.variation(
2 "show-about-us",
3 { key: "brian@launchdarkly.com" },
4 false
5);

And then pass that value as part of the page's props:

1return {
2 props: {
3 frontmatter: frontMatter,
4 markdownBody: markdownBody,
5 showPage: showPage,
6 },
7};

When the user hits this route but show-about-us is false, you can make it return a 404, as if the page doesn't even exist.

To do that, you must first import Next's error page:

1import ErrorPage from "next/error";

Now you can access the showPage prop that you passed and use it to return a 404.

Here is an example:

1export default function About({ frontmatter, markdownBody, showPage }) {
2 if (!showPage) return <ErrorPage statusCode="404" />;
3 return (
4 ...
5 );
6}

There are two important things to consider:

  1. You have now introduced a build impact to the show-about-us flag and will need to tag it so that the site is rebuilt when that flag is changed.
  2. Because you introduced a build impact, you cannot show different variations to different users. Either everyone will see the About Us page or no one will.

Incremental static regeneration (ISR) and distributed persistent rendering (DPR)

Because ISR and DPR are essentially just deferred static rendering, the integration is identical to the SSG integration. You create both an ISR or a DPR page the same way. The main difference is that ISR can have a timeout where the page gets re-rendered without a complete rebuild. With DPR, it only ever renders once per build. On Netlify, if you do not provide a timeout, it runs as DPR, but if you do, it runs as if it is SSR, as Netlify does not support ISR. Vercel, the creators of Next.js, has full support for ISR.

In the example below, you see a dynamic "catch all" route as /dpr/[[slug]].js. The folder name /dpr is just for example purposes and not required to use DPR. This page pulls the top 5 posts from the featured user as determined by the featured-username flag, and prerenders those. This is determined by only adding these 5 paths to the paths variable returned by getStaticPaths().

This page uses DPR/ISR because of the fallback: "blocking" line on the return instead of fallback: false. In a typical prerendered static path, fallback: false causes any path not returned in the paths variable to return a 404. However, with fallback: "blocking", any path not in the paths variable waits for the page to be generated and return that to the browser. To learn more, read the Next.js documentation.

Here is an example:

1export async function getStaticPaths() {
2 const client = await getClient();
3 let username = await client.variation(
4 "featured-username",
5 { key: "brian@launchdarkly.com" },
6 false
7 );
8
9 // only grab the first 5 to prerender
10 const top = 5;
11 const response = await fetch(
12 `https://dev.to/api/articles?username=${username}&page=1&per_page=${top}`
13 );
14 const data = await response.json();
15
16 const paths = data.map((post) => {
17 let username = post.organization
18 ? post.organization.username
19 : post.user.username;
20 let slug = `/dpr/${username}/${post.slug}`;
21 return slug;
22 });
23
24 return {
25 paths: paths,
26 fallback: "blocking",
27 };
28}

This route functions for any valid path even if it is not one of the top five that were returned in getStaticPaths(). You can see this in action by going to the deployed example sites on Netlify or Vercel and clicking one of the blog post links past the first five. The page will still render, though you may notice a slight delay compared to the first five.

The key thing to remember when you think about integrating with LaunchDarkly is that, regardless of whether the page uses DPR or ISR, the only way to ensure that the flag changes the page is to trigger a rebuild. Otherwise, your users may see the incorrect version of the page until a new build is triggered with DPR or until the timeout has triggered a rebuild of the page with ISR.

Conclusion

Combining Next.js with LaunchDarkly's feature management can be incredibly powerful. We only discussed a handful of possibilities here but hopefully this has already gotten you thinking about more.

To summarize, the key items to consider are:

  • What type of rendering are you integrating your flag into? SSG, SSR, client-side or DPR/ISR?
  • Which SDK do you need? Server-side Node.js should work for all cases except client-side rendering, which uses the React SDK.
  • Does your flag have build impact? This applies to flags connected to SSG or DPR/ISR. If so, tag it properly to automatically trigger a rebuild.
Want to know more? Start a trial.

Your 14-day trial begins as soon as you sign up. Learn to use LaunchDarkly with the app's built-in tutorial. You'll see how easy it is to manage the whole feature lifecycle from concept to launch to control.

Want to try it out? Start a trial.