skip to Main Content

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


  1. try to use 127.0.0.1 instead of localhost
    This should help

    Login or Signup to reply.
  2. Two Things:

    1. 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.

    2. Make sure Axios is sending cookies in its requests automatically:

    axios.get("http://localhost:5000/users/usersessions", { withCredentials: true });
    
    // or to enable for every request:
    
    axios.defaults.withCredentials = true
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search