In a project, I am allowing users to log in and then add notes to a database using React and Express. Currently, I am hosting the client side on GitHub Pages and the server on Railway. Everything is working except the server can’t access cookies when checking for authentication to fetch notes.
//client side Login
const checkUser = await fetch(`https://onotesbackend-production.up.railway.app/login`, {
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify(data)
})
//client side feching
const data = await fetch(`https://onotesbackend-production.up.railway.app/usernotes`, {
credentials: 'include',
method: "GET"
});
//server side index.js page
const port = 3000
main().catch(err => console.log(err));
async function main() {
await mongoose.connect("secreat");
}
const corsOptions = {
origin: ["https://mrd9877.github.io", "http://localhost:3001"],
credentials: true,
methods: "GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE",
allowedHeaders: ['Content-Type', 'Authorization', 'Content-Length', 'X-Requested-With', 'Origin', 'Accept'],
optionSuccessStatus: 200,
}
app.use(cors(corsOptions))
app.use(express.json({
type: ['application/json', 'text/plain']
}))
app.use(cookieParser())
app.use(session({
secret: 'Super secret secret',
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 60000 * 60,
httpOnly: false,
withCredentials: true,
sameSite: 'None',
},
store: MongoStore.create({
client: mongoose.connection.getClient()
})
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(router)
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
//login router
const router = Router();
router.post("/login", async (req, res) => {
const data = req.body
const findUser = await NewUser.findOne({ username: data.username })
if (!findUser) return res.sendStatus(401)
if (findUser.password !== data.password) {
res.sendStatus(401)
}
if (findUser.password === data.password) {
req.session.user = findUser.id
console.log("log in done")
console.log(req.sessionId)
res.sendStatus(200)
}
})
export default router
//fech user notes router
const router = Router();
let userid = null
function isAuthenticated(req, res, next) {
req.sessionStore.get(req.sessionID, async (err, sessionData) => {
console.log(req.sessionID)
if (err) {
res.send({ "msg": "please login to use this service" }).status(401)
return
}
if (sessionData !== null) {
userid = await sessionData.user;
next()
} else {
res.sendStatus(402)
}
})
}
router.get('/usernotes', isAuthenticated, async (req, res) => {
const findUser = await NewUser.findById(userid)
if (!findUser) {
res.send({ "msg": "invalid user" }).status(401)
return
}
const username = findUser.username
const findUserNotes = await Notes.find({ username: username }).exec()
res.send(findUserNotes)
})
I tried..
app.use((req, res, next) => {
const isSecure = req.secure || req.headers['x-forwarded-proto'] === 'https';
const cookieOptions = {
secure: isSecure,
httpOnly: true,
sameSite: 'Lax',
maxAge: 24 * 60 * 60 * 1000
};
res.cookie('user_id', '12345', cookieOptions);
next();
});