How to Create a Universal API Client in Next.js App Router with Cookie-Based Auth (Server & Client S
Unanswered
Asian black bear posted this in #help-forum
Asian black bearOP
I’m using Next.js App Router and need help creating a reusable API client.
Goal:
I want to build a common function or class to handle all API calls across my app.
Issue:
I’m storing the access token in cookies (HTTP-only). For authenticated API requests, I read the token using the cookies() function from next/headers and include it in the request headers.
This approach works only in server components, but I want my API client to be usable in both server and client components.
Question:
How can I design a single API client that works in both environments and still handles authentication properly using cookies?
Goal:
I want to build a common function or class to handle all API calls across my app.
Issue:
I’m storing the access token in cookies (HTTP-only). For authenticated API requests, I read the token using the cookies() function from next/headers and include it in the request headers.
This approach works only in server components, but I want my API client to be usable in both server and client components.
Question:
How can I design a single API client that works in both environments and still handles authentication properly using cookies?