Last active
May 28, 2021 18:01
-
-
Save EarlGeorge/10a354120656699dd5dc83079c4e6c33 to your computer and use it in GitHub Desktop.
Session data is stored server-side, and using session ID inside cookie for users in browser.. using MongoDB - express !
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require("express"); | |
const mongoose = require("mongoose"); | |
const session = require("express-session"); | |
const MongoStore = require("connect-mongo")(session); | |
// Create the Express application | |
var app = express(); | |
const dbString = "mongodb://localhost:27017/db"; | |
const dbOptions = { | |
useNewUrlParser: true, | |
useUnifiedTopology: true, | |
}; | |
const connection = mongoose.createConnection(dbString, dbOptions); | |
app.use(express.json()); | |
app.use(express.urlencoded({ extended: true })); | |
const sessionStore = new MongoStore({ | |
mongooseConnection: connection, | |
collection: "sessions", | |
}); | |
app.use( | |
session({ | |
secret: "some secret", | |
resave: false, | |
saveUninitialized: true, | |
store: sessionStore, | |
cookie: { | |
maxAge: 1000 * 60 * 60 * 24, // Equals 1 day | |
}, | |
}) | |
); | |
app.get("/", (req, res, next) => { | |
if (req.session.viewCount) { | |
req.session.viewCount = req.session.viewCount + 1; | |
} else { | |
req.session.viewCount = 1; | |
} | |
res.send( | |
`<h1>You have visited this page ${req.session.viewCount} times.</h1>` | |
); | |
}); | |
app.listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment