Skip to content

Commit 84efd0a

Browse files
Add feature flag example (#1065)
1 parent 51f0570 commit 84efd0a

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"use client";
2+
import { type Session } from "next-auth";
3+
import { notFound } from "next/navigation";
4+
import { isFlagEnabled, FEATURE_FLAGS } from "@/utils/flags";
5+
6+
const Content = ({ session }: { session: Session | null }) => {
7+
const flagEnabled = isFlagEnabled(FEATURE_FLAGS.FEATURE_FLAG_TEST);
8+
9+
if (!flagEnabled) {
10+
notFound();
11+
}
12+
13+
return (
14+
<div className="mx-auto max-w-2xl">
15+
<h1 className="text-lg">
16+
This page is behind a feature flag. It will work in development or when
17+
the flag is turned on.
18+
</h1>
19+
<p className="mt-8 text-sm">
20+
{session ? "User is logged in" : "User is not logged in"}
21+
</p>
22+
</div>
23+
);
24+
};
25+
26+
export default Content;
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import Content from "./_client";
2+
import { getServerAuthSession } from "@/server/auth";
3+
4+
export const metadata = {
5+
title: "This is a feature flag example",
6+
};
7+
8+
export default async function Page() {
9+
// Example of grabbing session in case it is needed
10+
const session = await getServerAuthSession();
11+
12+
return <Content session={session} />;
13+
}

utils/flags.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { posthog } from "posthog-js";
2+
3+
export const FEATURE_FLAGS = {
4+
FEATURE_FLAG_TEST: "feature-flag-test",
5+
// Add more feature flags as needed
6+
} as const;
7+
8+
export type FeatureFlagName =
9+
(typeof FEATURE_FLAGS)[keyof typeof FEATURE_FLAGS];
10+
11+
export function isDevEnvironment() {
12+
return (
13+
process.env.NODE_ENV === "development" ||
14+
(typeof window !== "undefined" && window.location.hostname === "localhost")
15+
);
16+
}
17+
18+
export const isFlagEnabled = (
19+
featureFlag: FeatureFlagName,
20+
disableDevCheck = false, // Disable dev check to force feature flag to be checked always
21+
) => {
22+
if (!disableDevCheck && isDevEnvironment()) {
23+
console.log("Feature flag check skipped in development environment");
24+
return true;
25+
}
26+
return posthog.isFeatureEnabled(featureFlag);
27+
};

0 commit comments

Comments
 (0)