Next.js Integration

Learn how to integrate feature flags into your Next.js applications

Getting Started with Next.js

Next.js bindings for MyFlags SDK. This package provides Next.js-specific functionality for feature flag management, including SSR support and automatic revalidation.

Installation

npm install @myflags/next

Quick Start

First, wrap your application with the MyFlagsProvider:

// app/layout.tsx
import { MyFlagsProvider } from "@myflags/next/client";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <MyFlagsProvider
      config={{
        apiKey: "your-api-key",
        projectId: "your-project-id",
        environment: "production",
      }}
    >
      {children}
    </MyFlagsProvider>
  );
}

Server-Side Rendering

For server-side rendering, you can use the getServerSideFlags function:

// app/page.tsx
import { type MyFlagsConfig } from "@myflags/next";
import { getServerSideFlags } from "@myflags/next/server";
import { MyFlagsProvider } from "@myflags/next/client";

const config: MyFlagsConfig = {
  apiKey: "your-api-key",
  projectId: "your-project-id",
  environment: "production",
};

export default async function Page() {
  const defaultFlags = await getServerSideFlags(config);

  return (
    <MyFlagsProvider defaultFlags={defaultFlags} config={config}>
      {children}
    </MyFlagsProvider>
  );
}

Usage in Components

Use the feature flags in your client components:

"use client";

import { useFlag, useFlags } from "@myflags/next/client";

function MyComponent() {
  // Get a single flag
  const isNewFeatureEnabled = useFlag("new_feature");

  // Or get all flags
  const flags = useFlags();

  return (
    <div>
      {isNewFeatureEnabled && <NewFeatureComponent />}
      {/* or */}
      {flags.newFeature && <NewFeatureComponent />}
    </div>
  );
}

Features

SSR Support

Works seamlessly with Next.js server-side rendering and App Router.

Type Safety

Full TypeScript support with type-safe flag names and values.

Automatic Revalidation

Flags are automatically updated when changes occur.

Efficient Caching

Server-side caching to minimize API calls.