Calling and Authenticated API from Next.js Server Side

Calling an authenticated API from Next.js server side is a little different than calling it from the client side and concerning authentication cookies.

When implementing authentication cookies and calling an authenticated API from the client side, the browser will automatically attach the authentication cookie and send it along to the API. However, the cookie needs to be added manually to the API request when working server side.

Next.js and getServerSideProps

From Next.js docs: “getServerSideProps is a Next.js function that can be used to fetch data and render the contents of a page at request time.”

getServerSideProps accepts a context parameter that can be used to access the request (req).

From the request object, we have access to the cookies array from which we can specify the cookie name to access the specific authentication cookie we need.

I have taken the example given on the Next.js docs and highlighted I’m adding the changes to send an authenticated request to an API.

import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'
 
type Repo = {
  name: string
  stargazers_count: number
}
 
export const getServerSideProps = (async context => {
  const AUTH_COOKIE_NAME = "MyAuthCookie";
  const cookie = context.req.cookies[AUTH_COOKIE_NAME];
  const res: Response = await fetch(
    'https://api.github.com/repos/vercel/next.js', 
    {
      method: 'GET',
      mode: 'cors',
      cache: 'force-cache',
      headers: {
        'Content-Type': 'application/json',
        cookie: `${AUTH_COOKIE_NAME}=${cookie}`,
      },
    }
  );
  const repo: Repo = await res.json()

  return { props: { repo } }
}) satisfies GetServerSideProps<{ repo: Repo }>

export default function Page({
  repo,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
  return (
    <main>
      <p>{repo.stargazers_count}</p>
    </main>
  )
}

More about getServerSideProps https://nextjs.org/docs/pages/building-your-application/data-fetching/get-server-side-props

If you liked this reading, share it on your social media and you can follow me on Twitter or LinkedIn.


Consider giving back by getting me a coffee (or a couple) by clicking the following button:

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.