Next.js Discord

Discord Forum

External api token authentication in server rendered components?

Unanswered
Broad-snouted Caiman posted this in #help-forum
Open in Discord
Broad-snouted CaimanOP
I authorize (login from a client component), through an endpoint, towards an external api that responds with a Set-Cookie header containing a token.

Therefore the token is not reachable from within the client/browser javascript, but further requests to the external api contains the cookie. But how would you use this token/cookie in subsequent requests from both client rendered components and server side rendered components? (Requests to external api made from your next server and your client)

You could forward the login request through your own route handler endpoint and get access to the cookie on the next server, then forward it to your client with the correct domain property. But how would I then also use this cookie/token from my server rendered components for subsequent requests to the external api?

5 Replies

Blackpoll Warbler
Hey mate, here's how I'm using it and it sorta works this way:

const token = nextCookies.get('token')
...
credentials: 'include',
headers: {
  'content-type': 'application/json',
  ...(token?.value && {
    Authorization: `JWT ${token.value}`,
  }),
},

in my fetch I include it like that, I say sorta because to be quite frank, caching hasn't been quite right with the app directory for me
Broad-snouted CaimanOP
Hi Paul, thanks for your answer. I don’t really understand, where do you set the cookie on the server?
Masai Lion
try:

const token = await axios.post(
${BaseUrl}/auth/refresh,
{},
{ withCredentials: true }
);
@Broad-snouted Caiman Hi Paul, thanks for your answer. I don’t really understand, where do you set the cookie on the server?
Blackpoll Warbler
Ahh, the login in our case is first handled entirely on client, so that the server sets the HTTP cookie, we don't mess with that step at all
but we read and set the cookie on subsequent requests or for middleware to limit access to certain pages