Skip to content

Commit 7d8cc70

Browse files
42atomysbalazsorban44
andauthoredMay 31, 2022
feat(middleware): support custom cookieName (#4385)
* feat: Add the support of custom cookieName on the next-auth/middleware * chore: Only accept used params based on NextAuthConfig * docs: Remove duplicated docs Co-authored-by: Balázs Orbán <info@balazsorban.com>
1 parent 75602a3 commit 7d8cc70

File tree

1 file changed

+22
-3
lines changed

1 file changed

+22
-3
lines changed
 

‎packages/next-auth/src/next/middleware.ts

+22-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { NextMiddleware, NextFetchEvent } from "next/server"
2-
import type { Awaitable, NextAuthOptions } from ".."
2+
import type { Awaitable, CookieOption, NextAuthOptions } from ".."
33
import type { JWT, JWTOptions } from "../jwt"
44

55
import { NextResponse, NextRequest } from "next/server"
@@ -22,6 +22,22 @@ export interface NextAuthMiddlewareOptions {
2222
*/
2323
pages?: NextAuthOptions["pages"]
2424

25+
/**
26+
* You can override the default cookie names and options for any of the cookies
27+
* by this middleware. Similar to `cookies` in `NextAuth`.
28+
*
29+
* Useful if the token is stored in not a default cookie.
30+
*
31+
* ---
32+
* [Documentation](https://next-auth.js.org/configuration/options#cookies)
33+
*
34+
* - ⚠ **This is an advanced option.** Advanced options are passed the same way as basic options,
35+
* but **may have complex implications** or side effects.
36+
* You should **try to avoid using advanced options** unless you are very comfortable using them.
37+
*
38+
*/
39+
cookies?: Partial<Record<keyof Pick<keyof NextAuthOptions["cookies"], "sessionToken">, Omit<CookieOption, "options">>>
40+
2541
/**
2642
* If a custom jwt `decode` method is set in `[...nextauth].ts`, the same method should be set here also.
2743
*
@@ -30,7 +46,6 @@ export interface NextAuthMiddlewareOptions {
3046
*/
3147
jwt?: Partial<Pick<JWTOptions, "decode">>
3248

33-
3449
callbacks?: {
3550
/**
3651
* Callback that receives the user's JWT payload
@@ -91,7 +106,11 @@ async function handleMiddleware(
91106
return NextResponse.redirect(errorUrl)
92107
}
93108

94-
const token = await getToken({ req, decode: options?.jwt?.decode })
109+
const token = await getToken({
110+
req,
111+
decode: options?.jwt?.decode,
112+
cookieName: options?.cookies?.sessionToken?.name
113+
})
95114

96115
const isAuthorized =
97116
(await options?.callbacks?.authorized?.({ req, token })) ?? !!token

0 commit comments

Comments
 (0)
Please sign in to comment.