1

I have an API route that requires a session cookie to test Authentication

/api/structure/[module]

When I try to connect this route with axios like:

const res = await axios.get(
    `http://localhost:3000/api/structure/${params.name}`,
    { withCredentials: true }
  );

it doesn't work.

I am using next-auth so here's the code to get the session:

import {getSession} from 'next-auth/client';

export default async function handler(req, res) {
    const session = await getSession({ req: req });
}

but it returns null for the session.

> The weird part is I can consume the route with the browser and it works just fine.

I think it has something to do with the httpOnly cookie or the CURL.

Yes I set withCredentials to true

And my cookie is httpOnly

I spent a week searching for a solution but I didn't manage to find any. Any help Please.

  • 1
    _"it doesn't work"_ - Could you be more specific? Do you get any errors in the console or network tab? Are you making the `axios` request from the client or server? – juliomalves Oct 25 '21 at 13:48
  • what I mean by it doesn't work is when I try to get the cookies from the request I get an empty object and I am using axios in the client side – Med El Mobarik Oct 25 '21 at 16:22
  • If the cookie is HttpOnly then it can't be access in the client-side. – juliomalves Oct 25 '21 at 16:50
  • But I want to send it to the server not get it in the client side (and I think this is something possible) – Med El Mobarik Oct 25 '21 at 17:03
  • Cookies should automatically be sent from the browser. Are you sure you're successfully logged-in before making the request? – juliomalves Oct 25 '21 at 17:24
  • I think I resolved the issue, the problem was that I used axios inside getServerSideProps() which is a server side code but when I use in the client side it works just fine. – Med El Mobarik Oct 25 '21 at 17:32
  • But is there any way to use axios in the server side code and also send the cookies stored in my browser ? – Med El Mobarik Oct 25 '21 at 17:34
  • 1
    Right, that makes sense. Cookies will not automatically be sent when the request is made from the server, you need to explicitly pass them. See [Why are cookies not sent to the server via getServerSideProps in Next.js?](https://stackoverflow.com/questions/69057271/why-are-cookies-not-sent-to-the-server-via-getserversideprops-in-next-js/69058105#69058105). – juliomalves Oct 25 '21 at 17:34
  • Well could you please show me how to explicitly pass the cookies via axios inside a server side code – Med El Mobarik Oct 25 '21 at 17:38
  • Thank you buddy I really appreciate your help ;) – Med El Mobarik Oct 25 '21 at 17:42

0 Answers0