Skip to content

Commit 4f67edd

Browse files
authored
Added example for setting cookie before redirect in middleware (#32542)
1 parent 738a964 commit 4f67edd

File tree

1 file changed

+74
-2
lines changed

1 file changed

+74
-2
lines changed

docs/api-reference/next/server.md

Lines changed: 74 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,13 +70,68 @@ import type { NextFetchEvent } from 'next/server'
7070

7171
## NextResponse
7272

73-
The `NextResponse` object is an extension of the native [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) interface, with the following added methods and properties:
73+
The `NextResponse` class extends the native [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) interface, with the following:
74+
75+
### Public methods
76+
77+
Public methods are available on an instance of the `NextResponse` class. Depending on your use case, you can create an instance and assign to a variable, then access the following public methods:
7478

7579
- `cookies` - An object with the cookies in the `Response`
76-
- `cookie` - Set a cookie in the `Response`
80+
- `cookie()` - Set a cookie in the `Response`
81+
- `clearCookie()` - Accepts a `cookie` and clears it
82+
83+
```ts
84+
import { NextResponse } from 'next/server'
85+
import type { NextRequest } from 'next/server'
86+
87+
export function middleware(request: NextRequest) {
88+
// create an instance of the class to access the public methods. This uses `next()`,
89+
// you could use `redirect()` or `rewrite()` as well
90+
let response = NextResponse.next()
91+
// get the cookies from the request
92+
let cookieFromRequest = request.cookies['my-cookie']
93+
// set the `cookie`
94+
response.cookie('hello', 'world')
95+
// set the `cookie` with options
96+
const cookieWithOptions = response.cookie('hello', 'world', {
97+
path: '/',
98+
maxAge: 1000 * 60 * 60 * 24 * 7,
99+
httpOnly: true,
100+
sameSite: 'strict',
101+
domain: 'example.com',
102+
})
103+
// clear the `cookie`
104+
response.clearCookie('hello')
105+
106+
return response
107+
}
108+
```
109+
110+
### Static methods
111+
112+
The following static methods are available on the `NextResponse` class directly:
113+
77114
- `redirect()` - Returns a `NextResponse` with a redirect set
78115
- `rewrite()` - Returns a `NextResponse` with a rewrite set
79116
- `next()` - Returns a `NextResponse` that will continue the middleware chain
117+
- `json()` - A convenience method to create a response that encodes the provided JSON data
118+
119+
```ts
120+
import { NextResponse } from 'next/server'
121+
import type { NextRequest } from 'next/server'
122+
123+
export function middleware(req: NextRequest) {
124+
// if the request is coming from New York, redirect to the home page
125+
if (req.geo.city === 'New York') {
126+
return NextResponse.redirect('/home')
127+
// if the request is coming from London, rewrite to a special page
128+
} else if (req.geo.city === 'London') {
129+
return NextResponse.rewrite('/not-home')
130+
}
131+
132+
return NextResponse.json({ message: 'Hello World!' })
133+
}
134+
```
80135

81136
All methods above return a `NextResponse` object that only takes effect if it's returned in the middleware function.
82137

@@ -86,6 +141,23 @@ All methods above return a `NextResponse` object that only takes effect if it's
86141
import { NextResponse } from 'next/server'
87142
```
88143

144+
### Setting the cookie before a redirect
145+
146+
In order to set the `cookie` _before_ a redirect, you can create an instance of `NextResponse`, then access the `cookie` method on the instance, before returning the response.
147+
148+
Note that there is a [Chrome bug](https://bugs.chromium.org/p/chromium/issues/detail?id=696204) which means the entire redirect chain **must** be from the same origin, if they are from different origins, then the `cookie` might be missing until a refresh.
149+
150+
```ts
151+
import { NextResponse } from 'next/server'
152+
import type { NextRequest } from 'next/server'
153+
154+
export function middleware(req: NextRequest) {
155+
const res = NextResponse.redirect('/') // creates an actual instance
156+
res.cookie('hello', 'world') // can be called on an instance
157+
return res
158+
}
159+
```
160+
89161
### Why does redirect use 307 and 308?
90162

91163
When using `redirect()` you may notice that the status codes used are `307` for a temporary redirect, and `308` for a permanent redirect. While traditionally a `302` was used for a temporary redirect, and a `301` for a permanent redirect, many browsers changed the request method of the redirect, from a `POST` to `GET` request when using a `302`, regardless of the origins request method.

0 commit comments

Comments
 (0)