Reputation: 169
For ExpressJs and NodeJs Assume I have 3 types of users in my application. Based on type of user(extracting from cookie), how to serve particular folder based on condition?
Say I have 3 folders x, y and z. I have condition which says for user_type x -> serve folder x contents. Same with y and z.
I tried following code but it didn't worked.
function checkCookieMiddleware(req, res, next) {
const req_cookies = cookie.parse(req.headers.cookie || '');
if(req_cookies.type){
if(req_cookies.type === "X"){
express.static(basePath + "/client/x");
}
else if(req_cookies.type === "Y"){
express.static(basePath + "/client/y");
}
else {
next();
}
}
else {
next();
}
}
app.use(checkCookieMiddleware, express.static(basePath + "/client/z"));
Upvotes: 0
Views: 131
Reputation: 6491
I found this NPM package - express-dynamic-static - that looks to do what you are looking for. If you don't want to pull in another dependency, the source code for it is fairly small, you could copy it as a custom middleware yourself.
If you were to use it, then I think you code might look something like this:
const express = require('express');
const dynamicStatic = require('express-dynamic-static')();
const app = express();
app.use(dynamicStatic);
function checkCookieMiddleware(req, res, next) {
const req_cookies = cookie.parse(req.headers.cookie || '');
if (req_cookies.type) {
if (req_cookies.type === 'X') {
dynamicStatic.setPath(basePath + '/client/x');
} else if (req_cookies.type === 'Y') {
dynamicStatic.setPath(basePath + '/client/y');
} else {
// Z
dynamicStatic.setPath(basePath + '/client/z');
}
}
next();
}
app.use(checkCookieMiddleware);
Upvotes: 1