Home > Software design >  Javascript - how to "redeclare" an identifier?
Javascript - how to "redeclare" an identifier?

Time:10-06

session is imported from express-session.

I also need to export session as its used by many modules.

Module parse failed: Identifier 'session' has already been declared

How to overcome this (I know redeclaring is not possible but is there an alternative?)?

import { getMongoClient } from '@/api-lib/mongodb';
import MongoStore from 'connect-mongo';
import session from 'express-session';
import { promisifyStore } from 'next-session/lib/compat';


const mongoStore = MongoStore.create({
  clientPromise: getMongoClient(),
  stringify: false,
});

const getSession = session({
  secret: process.env.SESSION_SECRET,
  resave: true,
  rolling: true,
  saveUninitialized: false,
  store: promisifyStore(mongoStore),
  cookie: {
    secure: process.env.NODE_ENV == "production" ? false : false ,
    maxAge: 1000 * 60 * 60 * 24 * 7, // 7 days
    sameSite: 'strict',
    //expires: new Date(Date.now()   (1000 * 60 * 60 * 24 * 7)),//7 days
  }
});

export default async function session(req, res, next) {
  await getSession(req, res);
  next();
}

CodePudding user response:

Two ways:

Rename the imported session

import expressSession from 'express-session';
...
const getSession = expressSession({...});

Export an anonymous function

export default async function(req, res, next) {
  await getSession(req, res);
  next();
}
  • Related