Skip to content

Instantly share code, notes, and snippets.

@s1moe2
Created November 26, 2021 15:57
Show Gist options
  • Save s1moe2/c8487866626b04c53faa0e7441681c5d to your computer and use it in GitHub Desktop.
Save s1moe2/c8487866626b04c53faa0e7441681c5d to your computer and use it in GitHub Desktop.
Basic usage of sessions in Express.js
const express = require("express")
const sessions = require("express-session")
const FileStore = require("session-file-store")(sessions)
const app = express()
app.use(sessions({
secret: "whatasecret",
saveUninitialized: false,
resave: false,
store: new FileStore({}),
}))
app.use(express.json())
app.post("/login", (req, res) => {
const { username, password } = req.body
if (!username || !password || username !== "donald" || password !== "duck") {
return res.status(401).send("unauthorized")
}
req.session.user = {
id: 1,
username: "donald",
requests: 1,
}
res.status(200).send("ok")
})
app.post("/logout", (req, res) => {
req.session.destroy()
return res.sendStatus(204)
})
app.get("/public", (req, res) => res.send("public route"))
app.get("/private", isLoggedIn, (req, res) => res.send("private route"))
app.listen(process.env.PORT || 3000, () => console.log(`listening on ${process.env.PORT || 3000}`))
function isLoggedIn(req, res, next) {
if (!req.session) return res.status(401).send("unauthorized")
next()
}
{
"name": "xpressession",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"express-session": "^1.17.2",
"session-file-store": "^1.5.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment