db-session
path: courses/express-node/db-session.md
- **fileName**: db-session
- **Created on**: 2024-06-29 18:03:20
using db and session for more contral for the data for app example
import { globalErrorHandling } from "./utlis/GlobalErrorHandler.mjs";
import cors from "cors";
import dotenv from 'dotenv';
import setDbSessions from "./connectDb.mjs";
dotenv.config();
/**
* @module app.route
* @param {Object} express - Express module
* @param {Object} app - Express app
*/
export default function initExpress(express, app) {
app.use(express.json());
// Express server that can parse URL-encoded data from a form submission and log it to the console. When you run this on a Linux system, the server will listen on port 3000 and handle form submissions sent to `/submit-form`
app.use(express.urlencoded({ extended: true }));
app.use(cors());
setDbSessions(app, process.env.DB_URL); // setting some config for db
app.get("/", (req, res) => {
console.log(req.session);
if ( req.session.visited ) req.session.visited++;
else req.session.visited = 1;
res.send(`<h1> welcome from yossef you visited this ${req.session.visited} </h1> `);
});
app.all("*", () => {
res.send("<h1>404 Not Found</h1>");
});
app.use(globalErrorHandling); // global error handle
};
db session func
import mongoose from "mongoose";
import MongoStore from "connect-mongo";
import session from "express-session";
//This enhances security and data integrity
mongoose.set("strictQuery", true);
// the app for express app and url for url in .env file
function setDbSessions(app, url) {
// connnect to db
mongoose.connect(url,{}).catch(error => console.log("App.js mongoose.connect error",error));
let db = mongoose.connection;
db.on('error', console.error);
db.once('open', function(){
console.log("App is connected to DB", db.name)
});
// starting setting some seession info
app.use(session({
secret: process.env.SESSION_SECRET, // secret for incrypt
resave: false, // if true save even if not modifie
saveUninitialized: flase, // if true save if new session only
store: MongoStore.create({ // The session store instance, defaults to a new `MemoryStore` instance.
client: mongoose.connection.getClient()
}),
cookie: {
maxAge: 1000 * 60 * 60 * 24 // setting cookies life
},
}));
}
export default setDbSessions;
explain some option in session:
resave ->
-
Forces the session to be saved back to the session store, even if the session was never modified during the request. Depending on your store this may be necessary, 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)
saveUninitialized ->
-
Forces a session that is "uninitialized" to be saved to the store. A session is uninitialized when it is new but not modified. Choosing
false
is useful for implementing login sessions, reducing server storage usage, or complying with laws that require permission before setting a cookie. Choosingfalse
will also help with race conditions where a client makes multiple parallel requests without a session.
store ->
-
The session store instance, defaults to a new
MemoryStore
instance.
continue:passport.md
before:dotfiles.md