Next.js Discord

Discord Forum

Adding passport session cookie to fetch

Unanswered
Arboreal ant posted this in #help-forum
Open in Discord
Arboreal antOP
Hey all,

I've implemented a passport strategy on my backend and I would like any fetch requests from my nextjs app to add the session cookie when making requests.

My current setup:
#next.config.js
  async rewrites() {
    return [
      {
        source: '/api/proxy/:path*',
        destination: `${BACKEND_REDIRECT_URL}/:path*`,
      },
    ]
  },


#fetch example
  const baseUrl = 'http://localhost:3000/api/proxy'; // really pulled from .env

  const res = await fetch(`${baseUrl}/auth/user-info`, {
    ...requestInitArgs,
    credentials: 'include'
  });


When I manually navigate to 'http://localhost:3000/api/proxy/auth/sign-in' I can sign in correctly, then I get redirected to my dashboard page. the dashboard page makes the above call but there's no session in the request.

Manually navigating to 'http://localhost:3000/api/proxy/auth/user-info' in the browser does include the session. So I'm thinking it's something wrong with my fetch.

The fetch is being called in a server component, do I need to somehow get the client cookies from the person requesting the server component, and then add that to the fetch call?

6 Replies

Arboreal antOP
After a bit of debugging it seems that it's a server components issue. When I make the fetch call from a client component it works correctly.

In my server component I can call cookies() and see the cookie I need to pass through. Is it possible to add these cookies into the fetch? Can it be done via some form of middleware?
Arboreal antOP
That works great in my server components 🙂 Thank you!
How would you suggest I get the same fetch working in both server and client components without having to redfine it?

I'm using codegen to define all the fetch's and it would be nice not to have to manually add in extracting the headers in server components. Would that be possible? Or would you suggest I generate a fetch lib for the server components, and maybe generate some SWR hooks for client components to use?
Arboreal antOP
Cool. And then I can listen for status 401 on either the fetch or swr, and trigger a redirect to the sign-in route 🙂 Thanks!
Arboreal antOP
Quick question while I have this help thread open. What's a neat way of handling errors via a toast in next?

I see there's an ErrorBoundary component in the docs (it's a class component, but should be fine) which I guess could wrap the app and render a toast with whatever the error message is. In some angular projects we had a piece of global state which was a queue with errors on it, that way if multiple got thrown it would display a series of toasts.

Handling that with both server and client components could be tricky though. Would a global context which is updated by the error boundary component(s) work?