I am trying to use sessions for the first time. I don't get any errors however the session keys seems to change every request. I have tried most stuff I can find on google on fixing this issue but it just wont work.
BACKEND SERVER
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const { pool } = require('./db');
const helmet = require('helmet');
const compression = require('compression');
const rateLimit = require('express-rate-limit');
const { body, check } = require('express-validator');
//Session imports
var session = require('express-session');
const app = express()
//Settings for sessions and such
const isProduction = process.env.NODE_ENV === 'production'
const BACKEND_URL = isProduction?"https://prodtesting.herokuapp.com":"http://localhost:3005"
const FRONTEND_URL = isProduction?"https://stunning-bavarois-0eef55.netlify.app":"http://localhost:3000"
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
const origin = {
origin: FRONTEND_URL,
credentials: true,
methods: ['POST', 'PUT', 'GET', 'OPTIONS', 'HEAD']
}
app.use(cors(origin))
app.use(compression())
app.use(helmet())
/* const limiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 5, // 5 requests,
}) */
/* app.use(limiter) */
/* const postLimiter = rateLimit({
windowMs: 1 * 60 * 1000,
max: 1,
}); */
//Session settings
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
cookie: { secure: true, maxAge:24*60*60*100}
}))
//Functions for getting
const getUsers = async () => {
try {
const users = await pool.query("SELECT * FROM users;")
return users;
}
catch (err) {
console.log(err)
return (500)
}
}
//Gets
app.get("/", (req, res) => {
res.send("Welcome to the home page of the API" + isProduction);
})
app.get("/users", (req, res) => {
res.send(getUsers())
})
app.get("/post",(req,res)=>{
if(req.session.firstpost){
res.send(req.session.firstpost);
}
else{
res.send(null)
}
})
app.post("/firstpost",(req,res)=>{
req.session.firstpost = req.body.firstpost;
res.status(200).send(req.session.firstpost)
})
app.listen(process.env.PORT || 3005, () => {
console.log(`Server listening` + process.env.PORT)
})
FRONT END
import { useEffect, useState } from 'react';
import './App.css';
import axios from 'axios';
axios.defaults.withCredentials = true
function App() {
const [user,setUser]=useState(null);
const [firstPost,setFirstPost] = useState(null)
const isProduction = process.env.NODE_ENV === 'production';
useEffect(()=>{
async function getUser(){
const data = await axios.get(isProduction?"https://prodtesting.herokuapp.com/users":"http://localhost:3005/", { withCredentials: true });
setUser(data.data);
}
async function getPost(){
const data = await axios.get(isProduction?"https://prodtesting.herokuapp.com/post":"http://localhost:3005/post", { withCredentials: true })
setFirstPost(data.data);
}
getPost()
getUser();
},[]);
const firstPostPost = async ()=>{
const data ={firstpost:"My first post"}
const response= await axios.post("http://localhost:3005/firstpost",data,{withCredentials:true});
setFirstPost(response.data)
}
return (
<div className="App">
<h1>Hello</h1>
<button onClick={firstPostPost}>first post</button>
{firstPost!==null&&<p>{firstPost}</p>}
{(user===false||user===null)?<><p>Please log in</p><a href={isProduction?"https://prodtesting.herokuapp.com/api/auth/steam/":"http://localhost:3005"}>Login</a></>:<p>{user.displayName}</p>}
</div>
);
}
export default App;
When I don const response= await axios.post("http://localhost:3005/firstpost",data,{withCredentials:true}); it stores it in the session. However when i request const data = await axios.get(isProduction?"https://prodtesting.herokuapp.com/post":"http://localhost:3005/post", { withCredentials: true }) it isn't there anymore