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
Show file tree
Hide file tree
Changes from 1 commit
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
26 changes: 26 additions & 0 deletions docs/docs/configuration/nextjs.md
Expand Up @@ -67,6 +67,32 @@ See the documentation for the [pages option](/configuration/pages) for more info

---

### `cookies`

- **Required**: _No_

#### Description

If you are using middleware to protect your routes and you use specific cookies in your NextAuth
specific cookies in your NextAuth configuration, or you want to use two different tokens for two different
for two different middlewares, you can specify the cookie in which the token is stored
the token.

:::note
Currently, only the `sessionToken` cookie can be overwritten
:::

#### Example (default value)
```js
cookies: {
sessionToken: {
name: `__s42.auth-token`,
}
}
```

---

### Examples

`withAuth` is very flexible, there are multiple ways to use it.
Expand Down
19 changes: 18 additions & 1 deletion packages/next-auth/src/next/middleware.ts
Expand Up @@ -21,6 +21,23 @@ export interface NextAuthMiddlewareOptions {
* [Documentation](https://next-auth.js.org/configuration/pages)
*/
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<NextAuthOptions["cookies"]>

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

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

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