#Is it possible to pass cookie headers from API calls to the browser?

13 messages · Page 1 of 1 (latest)

random aurora
#

Is it possible - when using the App router Next.js - to pass Cookie headers that are received from API calls on to the browser? And if so, what is the way for it?

EDIT: The api call is done from within a page (RSC) and not a route handler

visual glenBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

surreal rampart
#
export async function POST(request: NextRequest) {
  // ...your post request logic here

  // Set json response first
  const response = NextResponse.json(
    {
      ...userWithoutPassword,
    },
    { status: 200 }
  )

  // Then set a cookie
  response.cookies.set({
    name: 'jwt',
    value: token,
    httpOnly: true,
    maxAge: 60 * 60,
  })

  return response
}
random aurora
#

@surreal rampart Thanks for your reaction. Unfortunately that is not what we are looking for. The api call is done from within a page (RSC) and not a route handler

cyan seal
random aurora
cyan seal
#

can you do it with middleware?

random aurora
# cyan seal can you do it with middleware?

Not sure how to do that. When rendering the page, we execute certain API calls to another server. Each of those calls might send Set-Cookie headers in reply. And we need to pass those on to the browser.

cyan seal
#

or use server action with useEffect

random aurora
# cyan seal or use server action with useEffect

Do you mean we shouldn't execute the API call on SSR, but delay it until the browser runs the useEffect into a Server Action?
This wouldn't be desirable, since it negatively affects any page speed and might cause CLS.

cyan seal
#

I mean use server action with useEffect for setting the cookie

#

not rendering the page