Setting and sending http only cookies from Next.js 14 to Express.js

34 Views Asked by At

I have an express.js (node.js) as my backend, and next.js v. 14 as my frontend.

In the backend, I can send the cookie just fine, and I can protect certain endpoints also with the cookie. However, I cannot set the cookie in next.js. I followed numerous tutorials, but they didn't work for me (as many of them are using static data to set the cookie).

Here's my node.js app:

server.js:

app.use('/api/v1/admins', require('./controllers/adminController'));
app.use('/api/v1/users', require('./controllers/userController'));
app.get('/api/v1/data', tokenAuth, restrictTo('user'), catchAsync(async (req, res, next) => {
    return res.status(200).send({ message: 'DATA!', success: true });
}));

user controller:

router.post('/login', upload.none(), async (req, res, next) => {

    const { username, password } = req.body;

    if (password != "12345678") {
        return next(new AppError('Incorrect username or password!', 401));
    }
    const user_id = "1";

    const payload = { id: user_id, role: "user" };
    const jwt = JWT.sign(payload, secret, { algorithm: 'HS256', expiresIn: "7d" });

    res.cookie( "token", jwt, {
        httpOnly: true,
        sameSite: "lax"
        // secure: true // only works on https
    });

    return res.status(200).send({
        message: 'Logged in!',
        success: true
    });
});

I need to know how to set the http only cookie in next.js, how to send it for the backend again, and how to protect certain pages based on the cookie.

Thanks in advance...

0

There are 0 best solutions below