Skip to content

Commit 33db5af

Browse files
authored
fix(auth): scope OAuth session cookie via secure + AUTH_COOKIE_PREFIX (#377)
1 parent 10e8901 commit 33db5af

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

src/auth.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,34 @@ import {
88

99
const oryOAuth2Audience = process.env.ORY_OAUTH2_AUDIENCE
1010

11+
const useSecureCookies = process.env.VERCEL_ENV === 'production'
12+
// Standard Auth.js secure-cookie convention.
13+
const securePrefix = useSecureCookies ? '__Secure-' : ''
14+
// Cookies are scoped by host+path+name, NOT by port. Running two local
15+
// dashboards on different localhost ports makes them share the default
16+
// session cookie and clobber each other. AUTH_COOKIE_PREFIX lets each
17+
// instance use a distinct cookie name. Unset in prod/preview.
18+
const cookiePrefix = process.env.AUTH_COOKIE_PREFIX
19+
? `${process.env.AUTH_COOKIE_PREFIX}.`
20+
: ''
21+
1122
export const { handlers, auth, signIn, signOut } = NextAuth({
1223
// isolates from existing /api/auth/{callback,email-callback,verify-otp}
1324
basePath: '/api/auth/oauth',
1425
secret: process.env.AUTH_SECRET,
1526
session: { strategy: 'jwt' },
27+
useSecureCookies,
28+
cookies: {
29+
sessionToken: {
30+
name: `${securePrefix}${cookiePrefix}authjs.session-token`,
31+
options: {
32+
httpOnly: true,
33+
sameSite: 'lax',
34+
path: '/',
35+
secure: useSecureCookies,
36+
},
37+
},
38+
},
1639
// route handler that logs the failure and redirects to /sign-in so users
1740
// never see Auth.js's built-in error page; see oauth-recover/route.ts.
1841
pages: {

0 commit comments

Comments
 (0)