Skip to content

Commit 0829826

Browse files
authored
fix(auth): Prevent cached stale auth redirects in middleware (#244)
1 parent 9517392 commit 0829826

1 file changed

Lines changed: 18 additions & 8 deletions

File tree

‎middleware.ts‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,20 +38,30 @@ function parseFeatures(raw: string | undefined): Set<string> {
3838
return new Set();
3939
}
4040

41+
function noStore(response: NextResponse): NextResponse {
42+
response.headers.set("Cache-Control", "no-store, must-revalidate");
43+
return response;
44+
}
45+
46+
function redirectHome(request: NextRequest): NextResponse {
47+
return noStore(NextResponse.redirect(new URL(HOME_ROUTE, request.url)));
48+
}
49+
4150
export function middleware(request: NextRequest) {
4251
const { pathname } = request.nextUrl;
4352
const role = request.cookies.get(COOKIE_KEYS.ROLE)?.value;
4453
const features = parseFeatures(
4554
request.cookies.get(COOKIE_KEYS.FEATURES)?.value,
4655
);
47-
const isAuthenticated = role === "superuser" || role === "user";
56+
const hasApiKey = !!request.cookies.get(COOKIE_KEYS.API_KEY)?.value;
57+
const isAuthenticated = hasApiKey || role === "superuser" || role === "user";
4858
const isSuperuser = role === "superuser";
4959

5060
if (GUEST_ONLY_ROUTES.has(pathname)) {
5161
if (isAuthenticated) {
52-
return NextResponse.redirect(new URL(HOME_ROUTE, request.url));
62+
return redirectHome(request);
5363
}
54-
return NextResponse.next();
64+
return noStore(NextResponse.next());
5565
}
5666

5767
if (PUBLIC_ROUTES.has(pathname)) {
@@ -60,23 +70,23 @@ export function middleware(request: NextRequest) {
6070

6171
if (PATHNAME_STARTS_WITH.some((prefix) => pathname.startsWith(prefix))) {
6272
if (!isAuthenticated || !isSuperuser) {
63-
return NextResponse.redirect(new URL(HOME_ROUTE, request.url));
73+
return redirectHome(request);
6474
}
65-
return NextResponse.next();
75+
return noStore(NextResponse.next());
6676
}
6777

6878
if (!isAuthenticated) {
69-
return NextResponse.redirect(new URL(HOME_ROUTE, request.url));
79+
return redirectHome(request);
7080
}
7181

7282
const gated = FEATURE_GATED_PREFIXES.find(
7383
({ prefix }) => pathname === prefix || pathname.startsWith(`${prefix}/`),
7484
);
7585
if (gated && !features.has(gated.flag)) {
76-
return NextResponse.redirect(new URL(HOME_ROUTE, request.url));
86+
return redirectHome(request);
7787
}
7888

79-
return NextResponse.next();
89+
return noStore(NextResponse.next());
8090
}
8191

8292
export const config = {

0 commit comments

Comments
 (0)