How to set a cookie in client side in NextJS 13?
Asked Answered
H

1

7

I am working on a website that allows Student and Faculty Login. So far, only the student login part generates a JWT and I am trying to reach the protected route /student. You can check out the code here:

https://github.com/shivpreet16/event-junction

I am sending the JWT generated upon matching credentials in the response header from /api/submit.js as:

if (auth.checkPass(rowvals[0].stu_pass, data)) {
            const token=({
              token: jwt.sign(
                {
                  username: rowvals[0].stu_email,
                  admin: true,
                },
                KEY
              ),
            });
            // console.log(token)
            res.setHeader('Content-Type', 'application/json')
            res.setHeader('Authorization', token)
            res.setHeader("Set-Cookie",'token=${token}; Max-Age=604800; SameSite=Strict');
            res.setHeader("Path", '/student' );
            // res.status(200).json({ message: "Login successful" });
            res.send(JSON.stringify({ message: 'Logged in'}))
          } else res.send(JSON.stringify({ message: "Wrong Password" }));
        } else {
          res.send(err.message);
        }

Then, I receive the JWT from the response header at client-side in /components/Login.js, and try to set it in a cookie using setTokenCookie(token) function in the /utils/auth.js file.

const token = response.headers.get('Authorization')
        if(token){
            console.log("Login successful")
            setTokenCookie(token)
            console.log(getTokenCookie())
            router.push(response.headers.get('Path'))
        }
        else{
            const info = await response.json()
            console.log(info.message)
        }

However, getTokenCookie() function (also in /utils/auth.js) keeps returning null. I know the JWT token is reaching the client-side from response header as it logs Login successful. However, the cookie is null.

Kindly help

Herder answered 31/3, 2023 at 5:19 Comment(1)
I am using PostgreSQL for storing user dataHerder
T
10

in next-13 you could set the cookie in api functions with cookies-next. Cookie is generated when user logins. So when you send the credentials to the backend, after you validate credentials, you set the cookie

import { setCookie } from "cookies-next";

setCookie("cookieKey", value, { req, res, maxAge: 60 * 6 * 24 });

then you can access the cookie in client-side

  import { getCookie } from "cookies-next";

  const cookie = getCookie("cookieKey");
Tenderhearted answered 31/3, 2023 at 5:32 Comment(1)
``` setCookies(AUTH_KEY_NAME, mergedObject.token, { expires: new Date(new Date().setFullYear(new Date().getFullYear() + 1)), }); ```Cautious

© 2022 - 2024 — McMap. All rights reserved.