Search code examples
reactjsauthenticationcookiesnext.jsserver-side-rendering

In Next.js 13 with turbopack, how do I access cookies without getServerSideProps?


I have an app that persists some values in a cookie. I know that there are other tools such as useState, useContext, etc... but this particular app works with a library that stores information in a jwt so I have to read certain values by fetching the jwt. I am porting the app from next.js 12 (with webpack) to next.js 13 (with turbopack).

I've already ported the app structurally to fit the app style routing of next.js 13. My pages all go in their individual folders with sub layouts WITHIN the app directory, and I have a master layout and homepage directly in the app directory.

The old code for my protected page in next.js 12 looked like this:

protected.tsx

import type { NextPage } from 'next';
import { GetServerSideProps } from 'next';
import { useContext } from 'react';

//@ts-ignore
import Cookies from 'cookies';

const Protected: NextPage = (props: any) => {
  if (!props.authorized) {
    return (
      <h2>Unauthorized</h2>
    )
  } else {
  return (
    <div className="max-w-md">
      <h1 className="font-bold">This is the Protected Section</h1>
    </div>
  )}
}

export const getServerSideProps: GetServerSideProps = async ({ req, res, query }) => {
  const { id } = query
  const cookies = new Cookies(req, res)
  const jwt = cookies.get('<MY TOKEN NAME>')
  if (!jwt) {
    return {
      props: {
        authorized: false
      },
    }
  }

  const { verified } = <MY TOKEN SDK INSTANCE>.verifyJwt({ jwt })

  return {
    props: {
      authorized: verified ? true : false
    },
  }
}

export default Protected

I have this page moved into it's own directory now.

"getServerSideProps" isn't supported in Next.js 13 https://beta.nextjs.org/docs/data-fetching/fundamentals. The docs say "previous Next.js APIs such as getServerSideProps, getStaticProps, and getInitialProps are not supported in the new app directory." So how would I change my code to work in Next.js 13?

P.S. I know what it looks like but this cookie IS NOT HANDLING USER AUTHENTICATION. I understand that someone could alter the cookie and gain access to the protected page. This is just a small piece of a larger app with other security mechanisms that I have in place.


Solution

  • import { cookies } from "next/headers";
    

    this is next/headers.js cookie function

    function cookies() {
        (0, _staticGenerationBailout).staticGenerationBailout('cookies');
        const requestStore = _requestAsyncStorage.requestAsyncStorage && 'getStore' in _requestAsyncStorage.requestAsyncStorage ? _requestAsyncStorage.requestAsyncStorage.getStore() : _requestAsyncStorage.requestAsyncStorage;
        return requestStore.cookies;
    }
    

    this is making a request to the client side to get the cookie. In app directory, you are on the server and you can write this inside the component.

    const cookie = cookies().get("cookieName")?.value