Next.js Discord

Discord Forum

How to get cookies in the front end ?

Answered
Bombay-duck posted this in #help-forum
Open in Discord
Bombay-duckOP
hello everyone, i hope you're having a great day.
am having a problem in my project and i'll be more than happy if someone can please explain to me where am messing up.

in my backend i creat an api that handles the login with passport, and send a cookie with userId and userName if the login is succesfull
it works fine with postman,i get the cookies and the session works as it is intented too.

however, in the frontend when i try to get that cookie after logging in it returns null
i tried different libs, js-cookie, universal-cookies, and as a last resort i tried to get the cookie from document.cookie;
nothing seems to work, i asked gpt but it doesn't seem to understand what am doing wrong.

can you please help me with this issue ?
Answered by Bombay-duck
hey i found why i wasn't receiving cookies i just had to add
app.use(cors({
    origin: 'http://localhost:3000',
    credentials: true, <-------------
    exposedHeaders: ['Set-Cookie'],
}));


and in the frontend :

async function loginUser(email: string, password: string) {
  try {
    const userData = { email, password };
    const response = await fetch("http://localhost:4444/api/login", {
      method: "POST",
      credentials: "include", <----------------------
      body: JSON.stringify(userData),
      headers: { "Content-Type": "application/json" },
    });

with this the thread is solved
thanks again for taking time to help me !
View full answer

22 Replies

Chinese Egret
You cannot get cookies in the client and that is good. otherwise your site is voulnurable for XSS attacks
There is different ways of solving this, you could have a different endpoint to get user data by cookie
@riský i mean isn't that only if `HttpOnly` is enabled?
Chinese Egret
Yes, but i pursume it is for this. or should be
Bombay-duckOP
@riský i tried httponly : false and it's the same thing
and thanks for taking time to answer my question !
Chinese Egret
Only same domain can read the cookie in frontend. But I do not recommend setting httponly to false
yeah true, i just wanted to clarify the blanket can't you made it seem like 🙂 (but i see you meant shouldn't)
Bombay-duckOP
yeah i've read it and i only tried to set it to false to see if it was the problem, what would you suggest me to do in this case ?
Chinese Egret
I would create a new endpoint, maybe "/me" or "/user" and based on cookie and session value return data about the user
Then, for auth there is a lot to consider. But I like how T3 Theor explained it: Server should do all auth and authz! Ask server if user is valid, if user has correct role etc...
Bombay-duckOP
sorry if my question sounds dumb am still new to world of webdev and nextjs, but shouldn't the server send the cookie to the frontend to set a session ? or the session should be set only in the backend ?
Chinese Egret
That is correct, the server has to set the cookie on the client. But the client will send it to the server with all its requests
Bombay-duckOP
without reading it ?
Chinese Egret
Yeap, when cookie is httponly: true the client cannot read it. But the server can always read cookies
Bombay-duckOP
thank you so much for clarifying ! you rock man
so is your thread solved now?
or do you still have questions in context with it
Bombay-duckOP
Last question, correct me if am wrong, the user logs in it send a request to the server, the server sends back the information with a cookie,
this cookie is not ment to be read by the client side but sends back the server in each request to prove he's authenticated, am i getting it right ?
Chinese Egret
That right! Then ofc there is many other approaches to authentication. But auth is extremely interesting!
Would recommend next-auth if you would like to try out a auth library.
Bombay-duckOP
hey i found why i wasn't receiving cookies i just had to add
app.use(cors({
    origin: 'http://localhost:3000',
    credentials: true, <-------------
    exposedHeaders: ['Set-Cookie'],
}));


and in the frontend :

async function loginUser(email: string, password: string) {
  try {
    const userData = { email, password };
    const response = await fetch("http://localhost:4444/api/login", {
      method: "POST",
      credentials: "include", <----------------------
      body: JSON.stringify(userData),
      headers: { "Content-Type": "application/json" },
    });

with this the thread is solved
thanks again for taking time to help me !
Answer