Add Feature Flags to your Next.js application with a single React Hook. This package integrates your Next.js application with HappyKit Flags. Create a free happykit.dev account to get started.
useFlags
hooknpm install @happykit/flags
Configure your application in _app.js
.
// _app.js
import { configure } from '@happykit/flags';
configure({ clientId: process.env.NEXT_PUBLIC_FLAGS_CLIENT_ID });
If you don’t have a custom _app.js
yet, see the Custom App
section of the Next.js docs for setup instructions.
Create an account on happykit.dev
to receive your clientId
. You’ll find it in the Keys section of your project settings once you created a project.
Make sure the environment variable containing the clientId
starts with NEXT_PUBLIC_
so the value is available on the client side.
Store your clientId
in .env.local
:
# .env.local
NEXT_PUBLIC_FLAGS_CLIENT_ID=flags_pub_development_xxxxxxxxxx
Later on, don’t forget to also provide the environment variable in production.
There’s also a full walkthrough of the setup, which explains the setup in your project and in HappyKit Flags itself.
You can load flags on the client with a single useFlags
call.
// pages/foo.js
import { useFlags } from '@happykit/flags';
export default function FooPage(props) {
const flags = useFlags();
return flags.xzibit ? 'Yo dawg' : 'Hello';
}
Or with server-side rendering
// pages/foo.js
import { useFlags, getFlags } from '@happykit/flags';
export default function FooPage(props) {
const flags = useFlags({ initialFlags: props.initialFlags });
return flags.xzibit ? 'Yo dawg' : 'Hello';
}
export const getServerSideProps = async () => {
const initialFlags = await getFlags();
return { props: { initialFlags } };
};
configure(options)
options.clientId
(string) required: Your HappyKit Flags Client Idoptions.defaultFlags
(object) optional: Key-value pairs of flags and their values. These values are used as fallbacks in useFlags
and getFlags
. The fallbacks are used while the actual flags are loaded, in case a flag is missing or when the request loading the flags fails for unexpected reasons. If you don’t declare defaultFlags
, then the flag values will be undefined
.useFlag(options)
options.user
(object) optional: A user to load the flags for. The user you pass here will be stored in HappyKit for future reference and individual targeting. A user must at least have a key
. See the supported user attributes here.options.initialFlags
(object) optional: In case you preloaded user flags during server-side rendering or static site generation, provide the flags as initialFlags
. The client will then skip the initial request and use the provided flags instead. This allows you to get rid of loading states on the client.options.revalidateOnFocus
(object) optional: By default, the client will revalidate all feature flags when the browser window regains focus. Pass revalidateOnFocus: false
to skip this behaviour.This function returns an object containing the requested flags.
Provide any of these attributes to store them in HappyKit. You will be able to use them for targeting specific users based on rules later on (not yet available in HappyKit Flags).
key
(string) required: Unique key for this useremail
(string): Email-Addressname
(string): Full name or nicknameavatar
(string): URL to users profile picturecountry
(string): Two-letter uppercase country-code of user’s county, see ISO 3166-1getFlags
useFlag(user)
user
(object) optional: A user to load the flags for. The user you pass here will be stored in HappyKit for future reference. A user must at least have a key
. See a list of supported user attributes here.This function returns a promise resolving to an object containing requested flags.
You can provide a user
as the first argument. Use this to enable per-user targeting of your flags. A user
must at least have a key
property.
// pages/foo.js
import { useFlags } from '@happykit/flags';
export default function FooPage(props) {
const flags = useFlags({ user: { key: 'user-id' } });
return flags.xzibit ? 'Yo dawg' : 'Hello';
}
See here if you’re using server-side rendering
Or if you’re using prerendering
// pages/foo.js
import { useFlags, getFlags } from '@happykit/flags';
export default function FooPage(props) {
const flags = useFlags({
user: props.user,
initialFlags: props.initialFlags,
});
return flags.xzibit ? 'Yo dawg' : 'Hello';
}
export const getServerSideProps = async () => {
const user = { key: 'user-id' };
const initialFlags = await getFlags(user);
return { props: { user, initialFlags } };
};
See all supported user attributes
You can configure application-wide default values for flags. These defaults will be used while your flags are being loaded (unless you’re using server-side rendering). They’ll also be used as fallback values in case the flags couldn’t be loaded from HappyKit.
// _app.js
import { configure } from '@happykit/flags';
configure({
clientId: process.env.NEXT_PUBLIC_FLAGS_CLIENT_ID,
defaultFlags: { xzibit: true },
});
Being able to set initial flag values is the first step towards server-side rendering. When you pass in initialFlags
the flags will be set from the beginning. This is avoids the first request on the client.
// pages/foo.js
import { useFlags } from '@happykit/flags';
export default function FooPage(props) {
const flags = useFlags({ initialFlags: { xzibit: true } });
return flags.xzibit ? 'Yo dawg' : 'Hello';
}
// pages/foo.js
import { useFlags, getFlags } from '@happykit/flags';
export default function FooPage(props) {
const flags = useFlags({ initialFlags: props.initialFlags });
return flags.xzibit ? 'Yo dawg' : 'Hello';
}
export const getServerSideProps = async () => {
const initialFlags = await getFlags();
return { props: { initialFlags } };
};
// pages/foo.js
import { useFlags, getFlags } from '@happykit/flags';
export default function FooPage(props) {
const flags = useFlags({ initialFlags: props.initialFlags });
return flags.xzibit ? 'Yo dawg' : 'Hello';
}
export const getStaticProps = () => {
const initialFlags = await getFlags();
return { props: { initialFlags } };
};
You don’t even need to use useFlags
in case you’re regenerating your site on flag changes anyways.
HappyKit can trigger redeployment of your site when you change your flags by calling a Deploy Hook you specify.
// pages/foo.js
import { getFlags } from '@happykit/flags';
export default function FooPage(props) {
return props.flags.xzibit ? 'Yo dawg' : 'Hello';
}
export const getStaticProps = () => {
const initialFlags = await getFlags();
return { props: { initialFlags } };
};
Note that you lose some features like revalidation when you go for this plain approach. This also means visitor will only see the changes once your site is redeployed instead of right away.
revalidateOnFocus = true
: auto revalidate when window gets focused// pages/foo.js
import { useFlags, getFlags } from '@happykit/flags';
export default function FooPage(props) {
const flags = useFlags({ revalidateOnFocus: false });
return flags.xzibit ? 'Yo dawg' : 'Hello';
}
export const getStaticProps = () => {
const initialFlags = await getFlags();
return { props: { initialFlags } };
};
This example shows the full configuration with server-side rendering and code splitting.
// _app.js
import App from 'next/app';
import { configure } from '@happykit/flags';
configure({ clientId: process.env.NEXT_PUBLIC_FLAGS_CLIENT_ID });
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
// pages/profile.js
import * as React from 'react';
import { useFlags, getFlags, Flags } from '@happykit/flags';
import dynamic from 'next/dynamic';
const ProfileVariantA = dynamic(() => import('../components/profile-a'));
const ProfileVariantB = dynamic(() => import('../components/profile-b'));
export default function Page(props) {
const flags = useFlags({
user: props.user,
initialFlags: props.initialFlags,
});
return flags.profileVariant === 'A' ? (
<ProfileVariantA user={props.user} />
) : (
<ProfileVariantB user={props.user} />
);
}
export const getServerSideProps = async ({ req, res }) => {
// preload your user somehow
const user = await getUser(req);
// pass the user to getFlags to preload flags for that user
const initialFlags = await getFlags(user);
return { props: { user, initialFlags } };
};
@happykit/flags
includes type definitions. By default, flags returned from useFlags
and getFlags
have the following type:
type Flags = { [key: string]: boolean | number | string | undefined };
You can use @happykit/flags
without further configuration and get pretty good types.
However, all exported functions accept an optional generic type, so you can harden your flag definitions by defining a custom flag type. This allows you to define flag values explicitily.
// _app.tsx
import { configure } from '@happykit/flags';
type Flags = {
booleanFlag: boolean;
numericFlag: number;
textualFlag: string;
// You can lock textual and numeric flag values down even more, since
// you know all possible values:
// numericFlag: 0 | 10;
// textualFlag: 'profileA' | 'profileB';
};
// the types defined in "configure" are used to check "defaultFlags"
configure<Flags>({
endpoint: 'http://localhost:8787/',
clientId: 'flags_pub_272357356657967622',
defaultFlags: {
booleanFlag: true,
numericFlag: 10,
textualFlag: 'profileA',
},
});
// pages/SomePage.tsx
import { useFlags, getFlags } from '@happykit/flags';
type Flags = {
booleanFlag: boolean;
numericFlag: number;
textualFlag: string;
};
export default function SomePage(props) {
const flags = useFlags<Flags>({ initialFlags: props.flags });
flags.booleanFlag; // has type "boolean"
flags.numericFlag; // has type "number"
flags.textualFlag; // has type "string"
return <div>{JSON.stringify(flags, null, 2)}</div>;
}
export async function getServerSideProps() {
const initialFlags = await getFlags<Flags>();
initialFlags.booleanFlag; // has type "boolean"
initialFlags.numericFlag; // has type "number"
initialFlags.textualFlag; // has type "string"
return { props: { initialFlags } };
}
If you have two variants for a page and you only want to render one depending on a feature flag, you’re able to keep the client-side bundle small by using dynamic imports.
import * as React from 'react';
import { useFlags, getFlags } from '@happykit/flags';
import dynamic from 'next/dynamic';
const ProfileVariantA = dynamic(() => import('../components/profile-a'));
const ProfileVariantB = dynamic(() => import('../components/profile-b'));
export default function Page(props) {
const flags = useFlags({ user: { key: 'user_id_1' } });
// display nothing while we're loading
if (flags.profileVariant === undefined) return null;
return flags.profileVariant === 'A' ? (
<ProfileVariantA user={props.user} />
) : (
<ProfileVariantB user={props.user} />
);
}
You can even go one step further and preload the flags on the server, so that the client receives a prerenderd page.
Notice that the loading state is gone with that as well, since the flags are available upon the first render.
// with server-side flag preloading
import * as React from 'react';
import { useFlags, getFlags, Flags } from '@happykit/flags';
import dynamic from 'next/dynamic';
const ProfileVariantA = dynamic(() => import('../components/profile-a'));
const ProfileVariantB = dynamic(() => import('../components/profile-b'));
export default function Page(props) {
const flags = useFlags({
user: props.user,
initialFlags: props.initialFlags,
});
return flags.profileVariant === 'A' ? (
<ProfileVariantA user={props.user} />
) : (
<ProfileVariantB user={props.user} />
);
}
export const getServerSideProps = async ({ req, res }) => {
// preload your user somehow
const user = await getUser(req);
// pass the user to getFlags to preload flags for that user
const initialFlags = await getFlags(user);
return { props: { user, initialFlags } };
};
Author: happykit
Demo: https://happykit.dev/solutions/flags
Source Code: https://github.com/happykit/flags
#react #reactjs #javascript