Express Session with TypeScript
Required Packages
We’ll need the default “express-session” package from npm:
$ npm install -s express-session
After that, because we’re using TypeScript, so:
$ typings install -s -g dt~express-session
Note: You may want to search the typings source before install it with “dt~express-session” or “env~express-session” by:
$ typings search express-session
Extending the “Express.Request” Interface
Because “express-session” isn’t built-in, so we must extend the “Express.Request” interface so that we can use it in our controller. For your reference:
import * as Express from ‘express’;
export interface Request extends Express.Request {session: [any];
}
Injecting “express-session” into Express instance
To injecting the “express-session”, you can easily following the oficial guide of them, for your reference in TypeScript:
import * as Express from ‘express’;
import * as ExpressSession from ‘express-session’;
const instance = Express();
instance.use(ExpressSession({
secret: ‘i-love-husky’,
resave: false,
saveUninitialized: true
}));Using “express-session” in Controllers
After above setups, you’re able to use “express-session” in your controller. For your reference in TypeScript:
public static getIndex = async function (
request: Request,
response: Response,
next: NextFunction
) {
// Set the session content.
request.session[‘key-name’] = ‘Hello, world!’;
// Get the session content.
const sessionMessage = request.session[‘key-name’];
…
}
Hope you enjoy your TypeScript projects :)