express.session undefined in typescript

Viewed 2786

I am very new to typescript/javascript, I am trying to build backend rest apis with session following is app.ts file

import express from "express";
import { applyMiddleware, applyRoutes } from "./utils";
import routes from "./services";

const app = express();

    var ses= {
        secret: "secret_session",
        resave: true,
        saveUninitialized: true,
        cookie: { maxAge: 3600000,secure: false, httpOnly: true
}
if (app.get('env') === 'production') {
    app.set('trust proxy', 1)
    ses.cookie.secure = true
}

app.use(session(ses));

applyRoutes(routes, app);

I have started the server and applied the middlewares for error handling but those are not related to question in my opinion so I'm not adding code for it. Following is my routes.ts code where I'm trying to set the session.

import { Request, Response } from "express";
import { getAll, getByKeyword, addNewProduct } from "./productControllers";
{
path: "/api/v1/getAllProducts",
method: "get",
handler: [
  (req: Request, res: Response) => {
    getAll()
      .then((row: any) => {
       var sess = req.session;
       sess.views = 1;
        res.status(200).json({ data: row });
      })
      .catch(err => {
        res.json({
          message: err
        });
      });
  }
]
}

I'm getting error at sess.views = 1;

I have tried the suggested questions before asking it, none of them were of any help to me.

EDIT: I have created an index.ts

import searchRoutes from "./products/routes";

export default [...searchRoutes];

I have another util class

export const applyRoutes = (routes: Route[], router: Router) => {
  for (const route of routes) {
    const { method, path, handler } = route;
    (router as any)[method](path, handler);
  }
}
1 Answers

You are using an interface which is Request for express.js. But it doesn't have type definition for session. So typescript throws a compile error. To solve it you need to define session type under Request interface.

You could define a session.d.ts file under your project. And create required types & interfaces. Like:

declare global {
  namespace Express {
    interface Request {
      session?: Session;
      sessionID?: string;
    }
  }
}

interface Session{
  mySessionVarible:string
}

But the good thing is we have DefinitilyTyped project which you can find many type definitions. This needs to solve your compile problem.

npm install --save-dev @types/express-session

And don't forget to change your import for Request.

import { Request, Response } from "@types/express-session";
Related