Sling Academy
Home/Next.js/Next.js: How to Extract Request Headers (4 Approaches)

Next.js: How to Extract Request Headers (4 Approaches)

Last updated: April 27, 2023

This article shows you a couple of different ways to extract request headers in Next.js (we will focus on Next.js 13 and use TypeScript in the upcoming examples).

What are request headers?

Request headers are a part of the HTTP protocol that allows clients (such as web browsers) to send additional information about a request to the server. These headers provide metadata about the request, such as the content type, the content length, the user agent (browser), and other details. Servers use this information to process the request, respond appropriately, and apply any necessary optimizations.

Some common request header names include:

  • Accept: Specifies the content types the client is able to understand.
  • Authorization: Contains credentials for authenticating the user agent to access restricted resources.
  • Content-Type: Describes the media type of the request body.
  • Content-Length: Specifies the size of the request body in bytes.
  • User-Agent: Provides information about the client’s browser, operating system, and other details.

Extracting request headers in Next.js

Extracting request headers in server components

If you are using Next.js 13 and put your components and pages inside the app directory, they will be server components by default. In order to get request headers in a server component, you can use the headers() function from next/headers module. This function returns a read-only Web Headers object that allows you to access headers from incoming requests.

Example:

// slingacademy.com
// app/page.tsx

import { headers } from 'next/headers';

export default function Home() {
  const headersList = headers();
  const userAgent = headersList.get('user-agent');

  return (
    <div style={{ padding: '30px' }}>
      <b>User agent:</b> {userAgent}
    </div>
  );
}

Screenshot:

Extracting request headers in client components with getServerSideProps() and getStaticProps()

A client component is the one in the pages directory of your project or has the directive use client at the top of the component file.

If you want to get request headers in a client component, you can use the getServerSideProps() or getStaticProps() functions to pass them as props to your component. These functions have access to the req object, which has a headers property that contains the request headers.

Example:

// slingacademy.com
// pages/some-route.tsx
import type { GetServerSideProps, NextPage } from 'next';

interface PageProps {
  referer: string | undefined;
  userAgent: string | undefined;
  contentType: string | undefined;
}

export const getServerSideProps: GetServerSideProps<PageProps> = async ({
  req,
}) => {
  const referer = req.headers.referer;
  const userAgent = req.headers['user-agent'];
  const contentType = req.headers['content-type'];
  return {
    props: {
      referer,
      userAgent,
      contentType,
    },
  };
};

const Page: NextPage<PageProps> = ({ referer, userAgent, contentType }) => {
  return (
    <div>
      <p>Referer: {referer}</p>
      <p>User Agent: {userAgent}</p>
      <p>Content Type: {contentType}</p>
    </div>
  );
};

export default Page;

Extracting request headers in Route Handlers

Route Handlers are a new feature in Next.js 13+ that allows you to create custom request handlers for a given route using the Web Request and Response APIs. To get request headers in Route Handlers, you can use the request object that is passed as an argument to your handler function. This object has a headers property that contains the request headers:

// app/api/user/route.ts
export async function GET(request: Request) {
  const referer = request.headers.referer;
  const userAgent = req.headers['user-agent'];

  console.log(referer, userAgent);
  
  // other code
}

Alternatively, you can use the headers() function from the next/headers module to get a read-only Web Headers object that allows you to access the incoming request headers:

// app/api/user/route.ts
import { headers } from 'next/headers';

export async function GET() {
  const headersList = headers();
  const referer = headersList.get('referer');
  const userAgent = headersList.get['user-agent'];
  
  // do what you want with the headers (some might be undefined)
}

Extracting request headers in API Routes

If you want to use request headers in an API route, you can use the req object that is passed as an argument to your handler function. This object has a headers property that contains the information you need.

Example:

// pages/api/user.ts
import type { NextApiRequest, NextApiResponse } from 'next';

interface ResponseData {
  referer: string | undefined;
}

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
) {
  const referer = req.headers.referer;
  res.status(200).json({ referer });
}

Conclusion

You’ve learned more than one approach to getting and parsing headers from an incoming request in Next.js. Choose from them the one that fits your use case.

Next.js evolves very quickly with new updates being released constantly and new features being added constantly. Therefore, regularly update new knowledge about this web framework on Sling Academy. Feel free to leave a comment if you have any questions. Happy coding & have a nice day!

Next Article: Next.js 14: How to Access Search Params in Route Handlers

Previous Article: Next.js 14: Extracting Request Body in Route Handlers

Series: Route Handlers and API Routes in Next.js

Next.js

Related Articles

You May Also Like

  • Solving Next.js Image Component Error with CSS Classes
  • How to Use MUI (Material UI) in Next.js 14
  • Fixing Data Update Issues in Next.js Production
  • Fixing Next.js Undefined ENV Variables in Production Build
  • Solving Next.js SyntaxError: Unexpected token ‘export’
  • Next.js Error: Found Page Without a React Component as Default Export – How to Fix
  • Fixing Next.js Error: Blank Page on Production Build
  • Fixing Next.js Error when Importing SVGs: A Step-by-Step Guide
  • Next.js Issue: useEffect Hook Running Twice in Client
  • Fixing ‘self’ is not defined error in Next.js when importing client-side libraries
  • How to Dockerize a Next.js App for Production
  • How to set up Next.js with Docker Composer and Nginx
  • Solving Next.js CORS Issues: A Comprehensive Guide
  • Fixing Next.js Hydration Mismatch Error in Simple Ways
  • Next.js Error: Cannot use import statement outside a module
  • Next.js: How to Access Files in the Public Folder
  • Fixing Next.js Import CSS Error: A Simple Guide
  • Fixing LocalStorage Not Defined Error in Next.js
  • Fixing Next.js Error: No HTTP Methods Exported