Guide to changing request headers in Next.js

I'm looking to include a custom header in each server request.

My current approach involves utilizing middleware in the following manner:

export async function middleware(req: NextRequest): Promise<NextResponse> {
    req.headers.append('x-custom-header', '1337');
    return NextResponse.next();
}

Upon checking with console.log(req.headers), I can confirm that the custom request header has been successfully added:

BaseHeaders [Headers] {
    [Symbol(map)]: {
      accept: [ '*/*' ],
      'accept-encoding': [ 'gzip, deflate, br' ],
      'accept-language': [ 'en-GB,en-US;q=0.9,en;q=0.8' ],
      'cache-control': [ 'no-cache' ],
      connection: [ 'keep-alive' ],
      cookie: ...,
      host: ...,
      pragma: [ 'no-cache' ],
      referer: ...,
      ...,
      'x-custom-header': [ '1337' ]
    }
  }

However, despite adding the custom header, it does not reflect on the browser's request itself.

What could be causing this issue? Are there other methods available for modifying request headers in Next.js?

Answer №1

It appears that starting with the release of Next.js v13.0.0, there is now the capability to adjust request headers. You can find more information on this feature in the Next.js documentation.

Below is a snippet of code from the documentation demonstrating how to modify request headers:

// middleware.ts

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

export function middleware(request: NextRequest) {
  // 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
}

Answer №2

My solution involves middleware altering the header and reflecting the changes in getServerSideProps.

export async function modifyHeader(request: NextRequest) : Promise<NextResponse> {
    const response = NextResponse.next()
    response.headers.append("authorization", "token123")
    return response
}


//within the page component
export const getServerSideProps = wrapper.getServerSideProps(store => async (context) => {
    //checking the modified headers
    console.log(context.res.getHeaders())
    return {
      props: {}
    }
  }
});

Answer №3

Interesting question that sparked my curiosity, as I have delved into SPA architectures extensively but haven't explored the specifics of nextjs and its SSR capabilities.

EXPLORING CUSTOM HEADERS AND CROSS SITE REQUEST FORGERY

One approach to tackle your query is to consider other scenarios where custom headers are useful and seek a solution in nextjs. A relevant aspect relates to security, such as using a custom request header like example-csrf to prevent Cross-Site Request Forgery (CSRF) in API requests that modify data.

In my search for techniques within nextjs, I came across the next-csrf library, which seems promising for addressing your issue. Although my understanding is limited, it appears that this library assists in generating the necessary request header values:

  • The middleware class functions upon receiving the request on the website to create the header value

  • This value is then passed to React components for execution within the browser:

import { getCsrfToken } from '../lib/csrf';

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} csrfToken={getCsrfToken()} />
}
  • Furthermore, you can transmit this value from the browser through React views if necessary:
const response = await fetch('/api/protected', {
    'headers': {
        'XSRF-TOKEN': csrfToken,
    }
});

It might be beneficial to peruse some issues or feedback on the CSRF GitHub repository to gain insights for shaping your own resolution.

REFLECTING ON THE ARCHITECTURE ASPECTS

This exploration is intriguing, considering nextjs' reputation for enhancing SEO and similar aspects. It brings to mind older web technologies where developers grappled with transitioning between client-side and server-side code. Maintaining control over data requests serves as a crucial technical base.

For reference, at Curity, we offer resources focusing on SPA security, CDN deployment, and developer experience. Though we don't currently utilize SSR, our future discussions may delve deeper into SSR applications:

Answer №4

If you want to include custom headers in your application, you can do so similar to how you would add security headers. This can be achieved by utilizing the headers property within your next.config.js:

// next.config.js

// Define a list of security headers that you want to include
const customHeaders = []

module.exports = {
  async headers() {
    return [
      {
        // Add these specified headers to all routes within your app.
        source: '/:path*',
        headers: customHeaders,
      },
    ]
  },
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing MUI alongside Tailwind CSS in conjunction with NextJS: Here's a solution for resolving the transparent button issue without compromising the utilization of Tailwind CSS preflight

Currently working on a project built on top of a NextJS template using TailwindCSS. Struggling to integrate MUI components due to unexpected behavior with the button element (White Button error in NextJS Project). While I am aware of solutions suggesting ...

Regular intervals and asynchronous JavaScript and XML (AJAX) requests are

There is a simple chat tool in place to ensure the chat room stays updated: setInterval (loadLog, 2500); function loadLog(){ //Scroll height prior to the request var oldScrollHeight = document.getElementById("chatMessages").scrollHeight - 20; ...

When data is retrieved, the state value in Reactjs useEffect remains unchanged

I've encountered an issue while trying to set up a Protected Route in my application. The route should display only if the user is authenticated through an API call, but for some reason, the state value isn't updating correctly. Any suggestions o ...

A step-by-step guide on displaying content according to a template file in AngularJS

I am new to using angular js and need help with displaying specific content on a particular page of my web application. I have a HTML template (showContent.html) that generates all pages, but I only want to show certain content on the URL http://localhost/ ...

Is it possible to modify an HTML document on the server side using Node.js?

I am currently working on a website project. As part of this project, there is a Python script that is activated by the user through the UI and runs on the server to generate HTML files. These HTML files are then read by the node server and sent in full to ...

The tRPC setData hook is limited in its ability to access all data necessary for optimistic UI updates

As I integrate mutations using tRPC and React Query to optimistically update my UI upon adding a new item, I've encountered an issue. The problem lies in the query I'm updating, which requires specific properties like auto-generated IDs or datab ...

Handling exceptions in XMLHttpRequest.open() method

Here is a snippet of code I am working with: xhttp=new XMLHttpRequest(); xhttp.open("GET",doc_name,false); xhttp.send(); xmlDoc=xhttp.responseXML; if(xmlDoc==null) { xmlDoc=loadXMLDoc(defaultXml); } While this code functions properly by loading a defa ...

The cdkDropList in Angular's drag and drop feature does not support the application of element styles

Just wanted to share my experience in case it helps someone else out there! I've been working on an Angular project where I needed to create a Trello-like application. To enable dragging elements from one list to another, I installed the Angular cdk ...

Next.js - useEffect is failing to run at all

Struggling with integrating socket.io into my Next.js app, I decided to simplify my code and gradually add pieces back in. However, this only made things more confusing. The socket is kept in a context provider directly under the body tag in the root layo ...

JavaScript UDP pinger timeout using the dgram module for nodejs

Currently, I am enrolled in a course where we are tasked with coding a UDP pinger using Javascript with Node.js and Dgram. The assignment provided to us is as follows: Our objective is to create the client-side code for an application. This client should ...

When using the test() method in JavaScript with regular expressions, it may return true even if not all characters match, even when using

When attempting input validation in a textarea, I encountered the following issue: const re= /^[0-9A-Za-zÀ-ÿ\s\’\'\:\.\-\,\!\[\]\(\)\@\&\?]+?$/im; re.test(control.valu ...

Delivering create-react-app's build files through an express server

I am trying to serve the build files of my React app on another Express application. I have copied all the static files from the build folder to the public folder inside my Express application and have set up the following code: app.use(express.static(pat ...

I need a counter in my React application that is triggered only once when the page scrolls to a specific element

I've encountered a challenge with a scroll-triggered counter on a specific part of the page. I'm seeking a solution using React or pure JavaScript, as opposed to jQuery. Although I initially implemented it with states and React hooks, I've ...

Update an existing item or add a new one if it is not already present

I am attempting to create a functionality similar to canva.com, where users can select images from the sidebar and drop them anywhere in the "div", allowing multiple images with individual positions. However, when I use setState(prevState=>{return [...p ...

Retrieve all direct message channels in Discord using DiscordJS

I need to retrieve all communication channels and messages sent by a bot. The goal is to access all available channels, including direct message (DM) channels. However, the current method seems to only fetch guild channels. client.channels.cache.entries() ...

If there is a lack of text at the beginning, then insert the

I am currently trying to figure out a solution to automatically add our domain name if it is not included when entering the username. In the code snippet below for my form, I want the script to check if "domainname\" is present before the username. I ...

Utilize AJAX to insert information into a MySQL database when a checkbox is selected

Before I got stuck here, I took a look at how a similar question was implemented here I attempted to implement the code in order to insert data into a MySQL database when a checkbox is clicked. While it may have been easier to do this on form submission, ...

How can I limit the input of string values from a Node Express request query?

export type TodoRequest = { order?: 'asc' | 'desc' | undefined; } export const parseTodoRequest = (requestData: ParsedQs): TodoRequest => { return { order: requestData.order as 'asc' | 'desc' | u ...

Refresh tab controllers in Angular JS on every click event

Is there a way to refresh the tab controller every time a tab is clicked? Here's the current code: $scope.tabs = [ { id: 'tab1', title: 'tab1', icon: 'comments', templateUrl: 'tab1/tab1.tpl.html&ap ...

Exploring the world of reactive programming in JavaScript by transforming traditional AJAX calls into Bacon.js streams while incorporating

How can I develop a method to convert calls to the server API to a Bacon.js / RxJs stream while supporting pagination? With pagination, I aim to keep track of the last requested item index and retrieve the next set of items based on the page size to popul ...