Next.js Discord

Discord Forum

Include client cookie in server request

Unanswered
Siberian posted this in #help-forum
Open in Discord
SiberianOP
What is the best way to forward the client stored cookie to the server action.

The client browser has an auth_token cookie stored with the session token for the user. The user will navigate to a page that will make a request that requires authentication e.g. /private-user-stuff. The call is made to /api/some-authenticated-endpoint the page component, so this request is running on the server. The api is then taking the auth_token cookie from the request and parsing it and doing its checks.

How can I get that client auth_token cookie onto the request that is being sent from the server so that my api is able to authenticate that session token?

Basic example of current setup, just simple NextJs page with a fetch call:
// Page which will get some data that requires authenticated user

export async function doStuffWithApi() {
  // the backend is going to be checking for a cookie called auth_token on the request
  // because this request is being run server-side that cookie doesn't exist
  // somehow I need to forward the client cookie to this server request so that it can be authenticated by my backend
  const response = await fetch('/api/user-photos');
  return response.json();
}

export default async function Page() {
  const result = await doStuffWithApi();

  return <div>{result}</div>
}

7 Replies

American black bear
I am also wondering...
Atlantic salmon
Can you provide some code of the basic workflow?
SiberianOP
Sure, I will edit the post
SiberianOP
I guess one way forwards is to move the components that is going to be displaying any of this user authenticated stuff to a client component and then call a server action from inside that client component?
you can use cookies from next/headers to read the necessary cookie and forward it with the request:
import { cookies } from 'next/headers'

export async function doStuffWithApi() {
  const token = cookies().get('token')
  const response = await fetch('/api/user-photos', {
    headers: { cookie: `token=${token}` },
  })
  return response.json()
}
keep in mind that by reading data using next/headers you are making this segment dynamic
Asian black bear
Cookies, in their most basic form, are just a piece of data sent with every request.