NextJS authentication with existing cookie/token secured backend

NextJS is an incredible front end framework to make fast websites. It supports Server-side rendering as well as Static side generation.

If you are using some API with existing Authentication mechanism like Cookie/Bearer token then it might be tricky to make it work.

export const getServerSideProps = async (ctx) => {
  const response = await fetch(`https://mysite.com`);
  if (res.status >= 200 && res.status < 300) {
    const json = response.json();

    return { props: { json } };
  } else {
    return { props: { error: await res.text() } };
  }
};

The above code will fail if backend expect cookie/Header as header Mechanism, because browser cookies/headers wont be passed to backend

Solution: Pass the browser headers explicitly, You can pass it using fetch as follows. #
export const getServerSideProps = async (ctx) => {
  const response = await fetch(`https://mysite.com`,{
    headers: ctx.req.headers
  });
  if (res.status >= 200 && res.status < 300) {
    const json = response.json();

    return { props: { json } };
  } else {
    return { props: { error: await res.text() } };
  }
};

Since you've made it this far, sharing this article on your favorite social media network would be highly appreciated ! For feedback, please ping me on Twitter.

Published