How to use cookie inside `getServerSideProps` method in Next.js?

You can get the cookies from the req.headers inside getServerSideProps:

export async function getServerSideProps(context) {
  const cookies = context.req.headers.cookie;
  return {
    props: {},
  };
}

You could then use the cookie npm package to parse them:

import * as cookie from 'cookie'

export async function getServerSideProps(context) {
  const parsedCookies = cookie.parse(context.req.headers.cookie);
  return { props: {} }
}

Leave a Comment