Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add the support of custom cookieName on the next-auth/middleware #4385

Merged
merged 5 commits into from May 31, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 22 additions & 3 deletions packages/next-auth/src/next/middleware.ts
@@ -1,5 +1,5 @@
import type { NextMiddleware, NextFetchEvent } from "next/server"
import type { Awaitable, NextAuthOptions } from ".."
import type { Awaitable, CookieOption, NextAuthOptions } from ".."
import type { JWT, JWTOptions } from "../jwt"

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

/**
* You can override the default cookie names and options for any of the cookies
* by this middleware. Similar to `cookies` in `NextAuth`.
*
* Useful if the token is stored in not a default cookie.
*
* ---
* [Documentation](https://next-auth.js.org/configuration/options#cookies)
*
* - ⚠ **This is an advanced option.** Advanced options are passed the same way as basic options,
* but **may have complex implications** or side effects.
* You should **try to avoid using advanced options** unless you are very comfortable using them.
*
*/
cookies?: Partial<Record<keyof Pick<keyof NextAuthOptions["cookies"], "sessionToken">, Omit<CookieOption, "options">>>

/**
* If a custom jwt `decode` method is set in `[...nextauth].ts`, the same method should be set here also.
*
Expand All @@ -30,7 +46,6 @@ export interface NextAuthMiddlewareOptions {
*/
jwt?: Partial<Pick<JWTOptions, "decode">>


callbacks?: {
/**
* Callback that receives the user's JWT payload
Expand Down Expand Up @@ -91,7 +106,11 @@ async function handleMiddleware(
return NextResponse.redirect(errorUrl)
}

const token = await getToken({ req, decode: options?.jwt?.decode })
const token = await getToken({
req,
decode: options?.jwt?.decode,
cookieName: options?.cookies?.sessionToken?.name
})

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