Setting Headers
Indeed, with the NextResponse API, you can effectively manage both request and response headers. This capability has been available since Next.js version 13.0.0.
import { NextResponse } from 'next/server';
export function middleware(request) {
// Clone the request headers and set a new header `x-hello-from-middleware1`
const requestHeaders = new Headers(request.headers);
requestHeaders.set('x-hello-from-middleware1', 'hello');
// You can also set request headers in NextResponse.rewrite
const response = NextResponse.next({
request: {
// New request headers
headers: requestHeaders,
},
});
// Set a new response header `x-hello-from-middleware2`
response.headers.set('x-hello-from-middleware2', 'hello');
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