Calling and Authenticated API from Next.js Server Side
AI-generated image 1960s Server Room

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.

Article content
getServerSideProps

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


Crossposted from my blog: https://esausilva.com/2024/02/12/calling-and-authenticated-api-from-next-js-server-side/

Yes I've worked on Next with Auth Flow

Like
Reply

To view or add a comment, sign in

More articles by 🚀 Esau S.

Explore content categories