Skip to content

Commit

Permalink
feat(middleware): support custom cookieName (#4385)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
42atomys and balazsorban44 committed May 31, 2022
1 parent 75602a3 commit 7d8cc70
Showing 1 changed file with 22 additions and 3 deletions.
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

0 comments on commit 7d8cc70

Please sign in to comment.