Skip to content

Instantly share code, notes, and snippets.

@CDT

CDT/server.js Secret

Created March 3, 2023 09:31
express-session example
const express = require('express')
const session = require('express-session')
const app = express()
// express-session connects session with request by the session ID(name is `connect.sid`) cookie
// Set up session middleware
app.use(session({
secret: 'very-secret-cookie', // secret is necessary to encrypt the session ID
// resave: save the session back to session store.
// but it can also create race conditions where a client makes two parallel requests to your server and changes made to the session
// in one request may get overwritten when the other request ends, even if it made no changes (this behavior also depends on what store you're using).
// setting it to false can boost the performance. in most cases just set it to true.
resave: false,
// saveUnitialized: save empty/unmodified session to session store.
// useful when you want to create a session to a user not yet logged in, which is helpful for tracking user behavior
// setting it to true can hev security flaws and performance issues
saveUninitialized: false,
}))
// Define a route that sets a session variable
app.get('/set-username', (req, res) => {
req.session.username = req.query.username
res.send(`username set to ${req.session.username}`)
})
// Define a route that retrieves a session variable
app.get('/get-username', (req, res) => res.send(`Username: ${req.session.username}`))
// Start the server
app.listen(3000, () => {
console.log('Server started on port 3000')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment