Next.js Discord

Discord Forum

How to use http only cookie with SWR?

Unanswered
Red wood ant posted this in #help-forum
Open in Discord
Red wood antOP
Hi,
I’m trying to access http only cookie through route handler for each request but for each request it will hit the route handler then fetch my api using swr.
I think this is wrong approach so what is the best way to handle this?
Thanks in advance a

23 Replies

Rose-breasted Grosbeak
trying to access http only cookies

What? You can't access them with js.

edit2: Edit: ah my bad, you're talking about a route handler
Holland Lop
Have you tried:

import { cookies } from "next/headers";
@Holland Lop Have you tried: `import { cookies } from "next/headers";`
Red wood antOP
needs action server or route handler which i mentioned above
which calls middleware/ api on server side for each request
@Holland Lop If I'm right, cookies from next/header would work!
Red wood antOP
it only works on server side i want it on client side
https://nextjs.org/docs/app/api-reference/functions/cookies
May I know what you're trying to achieve?
I meant, what you're gonna do with this cookie?
Or purpose of retrieving the cookie?
@Holland Lop Or purpose of retrieving the cookie?
Red wood antOP
for authentication i need to send access token otherwise the api will return unauthorized
Holland Lop
Are you using Axios?
Holland Lop
If yes, you can include an additional parameter with your API request withCredentials: true, and it will automatically includes cookies with your request.
import axios from 'axios';

const getData = async () => {
  try {
    const response = await axios.get('https://example.com/v1/data', {
      withCredentials: true,
    });

    console.log('Response:', response);
  } catch (error) {
    console.error('Error:', error);
  }
};
Holland Lop
In fetch, use credentials: 'include'
fetch('https://example.com/v1/data', {
  method: 'GET',
  credentials: 'include',
})
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error('Error:', error));
Red wood antOP
will i be able to put it in authorization?
@Holland Lop In fetch, use `credentials: 'include'`
Red wood antOP
?
@Red wood ant will i be able to put it in authorization?
Holland Lop
I'm not clear. In authorization?
@Holland Lop I'm not clear. In authorization?
Red wood antOP
Authorization header
Holland Lop
Simply adding credentials: 'include' in the object along with method will do the job. All cookies will be included with the API request.