Reputation: 11197
I have a simple application that uses an express session. Here is my entry script where I initiate the session.
export const app = express();
export const server = Server(app);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({
secret: "changed to nonsense string for this question",
resave: true,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}));
app.use('/api/v1/auth', require('./users'));
According to the documents of express-session, I should be able to access this via req.session. I want to get the secret key for use creating a json token within one route. Here is what I do:
export const routes = Router();
routes.post('/login', function (req, res, next) {
// ...
const token = jwt.sign(user, req.session.secret, { expiresIn: '5m' });
});
export default routes;
However, it consistently says that the req.session.secret
is not defined. What am I doing wrong? How do I access the session secret within a route?
Upvotes: 0
Views: 176
Reputation: 203514
secret
is part of the configuration of express-session
, but it's not accessible through req.session
(I think this is done on purpose).
How to access it from your route depends on where you're getting the secret from in the first place. Usually this is from an environment or configuration variable, and I don't see why you can't access those from your route handler directly.
If the secret is hardcoded, and you want to keep it that way, you can create a separate module for it that can be require()'d wherever you need the secret.
Upvotes: 1