Reputation: 67
I have created a cookie in express/node.js
var express = require('express');
var cookieParser = require('cookie-parser')
var app = express();
app.use(cookieParser())
app.use(function (req, res, next) {
// check if client sent cookie
var cookie = req.cookies.mainCookie;
if (cookie === undefined){
// no: set a new cookie
var randomNumber=Math.random().toString();
randomNumber=randomNumber.substring(2,randomNumber.length);
res.cookie('cookieName',randomNumber, {
maxAge: 60 * 60 * 24
httpOnly: true
});
console.log('cookie created successfully', randomNumber);
} else {
// yes, cookie was already present
console.log('cookie exists', cookie);
}
next();
});
then, I can access this cookie, like req.cookie
but can't do document.cookie
in front-end.
I would like to access it in front-end (JavaScript) Is it possible?
Upvotes: 0
Views: 1109
Reputation: 707158
When you set:
httpOnly: true
on the cookie, you are telling the browser that browser Javascript is not allowed to have access to the cookie, that the cookie should only be stored locally and sent to the server as required.
If you want browser Javascript to have access, then change to:
httpOnly: false
I would like to access it in front-end (JavaScript) Is it possible?
Yes, it is possible. Don't set httpOnly: true
.
If you want to read about this, you can read the MDN page on cookies where it has this:
To prevent cross-site scripting (XSS) attacks, HttpOnly cookies are inaccessible to JavaScript's Document.cookie API; they are only sent to the server. For example, cookies that persist server-side sessions don't need to be available to JavaScript, and the HttpOnly flag should be set.
Upvotes: 2