#Custom headers based on HTTP Response status code of the page

1 messages · Page 1 of 1 (latest)

cursive karma
#

Hi Everyone,

Do you have any idea how to return a different header based on status code of the page ?
For example I have a page when it's 200 (Success case) I want to return a specific header
When it's a 500 I want to return another header

https://github.com/vercel/next.js/discussions/75515#discussion-7897673

GitHub

Description I’m using Next.js 14 with the App Router, and I want to set custom HTTP header based on the final response status of a page. Specifically, I have a page.tsx where I export const dynamic...

carmine rootBOT
#

Hi @cursive karma. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To add custom headers based on the HTTP response status code of a page in Next.js, you can use middleware. Middleware allows you to modify the response before it's sent to the client. Here's how you can achieve this:

  1. Create a middleware.ts file in the root of your project (or in the src directory if you're using one).

  2. In this file, you can use the NextResponse API to check the status code of the response and add headers accordingly.

Here's an example of how you can implement this:

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export async function middleware(request: NextRequest) {
  const response = NextResponse.next();

  // Wait for the response to be generated
  await response.clone().text();

  if (response.status === 200) {
    response.headers.set('x-success-header', 'This is a success');
  } else if (response.status === 500) {
    response.headers.set('x-error-header', 'This is an error');
  }

  return response;
}

In this example:

  • We use NextResponse.next() to get the response that would normally be returned.
  • We wait for the response to be generated using await response.clone().text().
  • We then check the status of the response and set appropriate headers using response.headers.set().
  • Finally, we return the modified response.

This middleware will run for all routes in your application. If you want to limit it to specific routes, you can add a matcher configuration to your middleware file:

export const config = {
  matcher: '/api/:path*',
}

This approach allows you to add custom headers based on the status code of the response. However, please note that this method may not work for static pages or pages with static generation, as the response is generated at build time for those pages.

#

@cursive karma Kapa.ai is still learning and improving, please let me know how I did by reacting below.