How to use Cookies In Next.js
Cookies function as standard headers. During a request, they reside in the Cookie header, while in a response, they are located within the Set-Cookie header. Next.js simplifies cookie management with its cookies extension on NextRequest and NextResponse.
For incoming requests, cookies offer the following methods: get, getAll, set, and delete, enabling you to retrieve, manipulate, and remove cookies. You can verify the presence of a cookie with has or clear all cookies with remove.
For outgoing responses, cookies provide methods such as get, getAll, set, and delete, facilitating the handling and modification of cookies before sending the response.
import { NextResponse } from 'next/server';
export function middleware(request) {
// Assume a "Cookie:nextjs=fast" header to be present on the incoming request
// Getting cookies from the request using the `RequestCookies` API
let cookie = request.cookies.get('nextjs');
console.log(cookie); // => { name: 'nextjs', value: 'fast', Path: '/' }
const allCookies = request.cookies.getAll();
console.log(allCookies); // => [{ name: 'nextjs', value: 'fast' }]
request.cookies.has('nextjs'); // => true
request.cookies.delete('nextjs');
request.cookies.has('nextjs'); // => false
// Setting cookies on the response using the `ResponseCookies` API
const response = NextResponse.next();
response.cookies.set('vercel', 'fast');
response.cookies.set({
name: 'vercel',
value: 'fast',
path: '/',
});
cookie = response.cookies.get('vercel');
console.log(cookie); // => { name: 'vercel', value: 'fast', Path: '/' }
// The outgoing response will have a `Set-Cookie:vercel=fast;path=/` header.
return response;
}
Middlewares in Next.js
NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. One of its features is Middleware. In this article, we will learn about the middleware in Next.js with examples.
Table of Content
- Middleware in Next.js
- Benefits of Middleware
- Convention
- Matching Paths
- NextResponse
- Using Cookies
- Setting Headers
- CORS
- Producing Response
Contact Us