I am making an online forum. I tried to login and after checking the data, the server sends a server side cookie, then it uses a basic React.useEffect
to get the value from another path in node to extract the sessionId but no cookie gets registered in firefox.
App.js
:
const express = require('express')
var cors = require('cors');
const app = express()
const forumpage = require("./routes/forumpage")
const peopleroute = require("./routes/users")
const cookieParser = require('cookie-parser');
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
app.use(cookieParser())
app.use(cors({
origin: 'http://localhost:3000', // Replace with your frontend URL
credentials: true // Allows cookies to be sent with requests
}));
app.use("/users", peopleroute)
app.use("/forumpage", forumpage)
app.listen(5000, () => {
console.log("App runs on port 5000")
})
Cookie line of the login post function
res.cookie('sessionId', 'sessionId', {
httpOnly: true, // Makes the cookie inaccessible via JavaScript on the
});
Trying to get the session id from frontend (this is in the backend):
const usernames = async (req, res) => {
console.log(req.cookies.sessionId)
res.send(req.cookies.sessionId)
}
Frontend part that calls the last function:
const [user, setUser] = React.useState([])
React.useEffect(() => {
axios.get("http://localhost:5000/users/usersessions").then((response) => {
setUser(response.data)
})
}, [])
console.log(user)
2
Answers
try to use 127.0.0.1 instead of localhost
This should help
Two Things:
When using localhost, the cookie does not seem to be accepted by some browsers. So better run your frontend application on some domain name. You can follow this stackoverflow answer to achieve the same.
Make sure Axios is sending cookies in its requests automatically: