← coderrocketfuel.com

Get a User's Cookie Data Before the Page Loads in Next.js

How can you get a user's cookie data before the page loads in a Next.js application?

To do this, you need to access the req.headers.cookie string in the getInitialProps() function in your page.

static async getInitialProps ({req}) {
  const cookieString = req.headers.cookie;

  return {};
};

The req object contains the HTTP request object data, which is where the user's cookie data is held.

req.headers.cookie will contain the user's browser cookie data in the form of a string.

getInitialProps() is called on the server-side and before the page loads.

This data would otherwise not be available to the web page. But, since getInitialProps() is server-side code, this data is available.

Here's what the code would look like in a Next.js page:

import React from "react";

function Page() {
  return (
    <div>Page content</div>
  );
}

Page.getInitialProps = async ({ req }) => {
  const cookieString = req.headers.cookie;

  return {

    . . .

  };
};

export default Page;

Thanks for reading and happy coding!