cookies
The cookies
function allows you to read the HTTP incoming request cookies from a Server Component or write outgoing request cookies in a Server Action or Route Handler.
Good to know:
cookies()
is a Dynamic Function whose returned values cannot be known ahead of time. Using it in a layout or page will opt a route into dynamic rendering at request time.
cookies().get(name)
A method that takes a cookie name and returns an object with name and value. If a cookie with name
isn't found, it returns undefined
. If multiple cookies match, it will only return the first match.
import { cookies } from 'next/headers';
export default function Page() {
const cookieStore = cookies();
const theme = cookieStore.get('theme');
return '...';
}
cookies().getAll()
A method that is similar to get
, but returns a list of all the cookies with a matching name
. If name
is unspecified, it returns all the available cookies.
import { cookies } from 'next/headers';
export default function Page() {
const cookieStore = cookies();
return cookieStore.getAll().map((cookie) => (
<div key={cookie.name}>
<p>Name: {cookie.name}</p>
<p>Value: {cookie.value}</p>
</div>
));
}
cookies().has(name)
A method that takes a cookie name and returns a boolean
based on if the cookie exists (true
) or not (false
).
import { cookies } from 'next/headers';
export default function Page() {
const cookiesList = cookies();
const hasCookie = cookiesList.has('theme');
return '...';
}
cookies().set(name, value, options)
A method that takes a cookie name, value, and options and sets the outgoing request cookie. This method is only available in a Server Action or Route Handler.
import { cookies } from 'next/headers';
async function create(data) {
'use server';
cookies().set('name', 'lee');
// or
cookies().set('name', 'lee', { secure: true });
// or
cookies().set({
name: 'name',
value: 'lee',
httpOnly: true,
path: '/',
});
}