Repository: iamolegga/nestjs-session Branch: master Commit: cee9ba6dd773 Files: 58 Total size: 58.5 KB Directory structure: gitextract_yuzb6sdt/ ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.md │ │ ├── feature_request.md │ │ └── question.md │ ├── dependabot.yml │ └── workflows/ │ ├── build-lint-test.yml │ ├── on-pr-master.yml │ ├── on-push-master.yml │ ├── on-release.yml │ ├── publish-alpha.yml │ ├── publish-coverage.yml │ └── publish-with-git-tag-version.yml ├── .gitignore ├── .mergify.yml ├── .prettierrc ├── .vscode/ │ └── settings.json ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── __tests__/ │ ├── forRoot.spec.ts │ ├── forRootAsync.spec.ts │ ├── retires.spec.ts │ ├── routing.spec.ts │ └── utils/ │ ├── platforms.ts │ └── request.ts ├── eslint.config.cjs ├── examples/ │ ├── in-memory/ │ │ ├── .eslintrc.js │ │ ├── .gitignore │ │ ├── .prettierrc │ │ ├── README.md │ │ ├── nest-cli.json │ │ ├── package.json │ │ ├── src/ │ │ │ ├── app.controller.ts │ │ │ ├── app.module.ts │ │ │ └── main.ts │ │ ├── tsconfig.build.json │ │ └── tsconfig.json │ └── redis-store/ │ ├── .eslintrc.js │ ├── .gitignore │ ├── .prettierrc │ ├── README.md │ ├── nest-cli.json │ ├── package.json │ ├── src/ │ │ ├── app.controller.ts │ │ ├── app.module.ts │ │ ├── config.module.ts │ │ ├── config.service.ts │ │ ├── main.ts │ │ ├── redis.module.ts │ │ └── session.module.ts │ ├── tsconfig.build.json │ └── tsconfig.json ├── jest.config.js ├── package.json ├── src/ │ ├── index.ts │ └── retriesMiddleware.ts ├── tsconfig.build.json └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Bug report about: Create a report to help us improve title: "[BUG] " labels: bug assignees: iamolegga --- [ ] I've read [the docs](https://github.com/iamolegga/nestjs-session/blob/master/README.md) [ ] I've read [the docs of express-session](https://github.com/expressjs/session/blob/master/README.md) [ ] I couldn't find the same [bug](https://github.com/iamolegga/nestjs-session/issues?q=is%3Aissue+label%3Abug) **What is the current behavior?** **What is the expected behavior?** **Please provide minimal example repo. Without it this issue will be closed** **Please mention other relevant information such as Node.js version and Operating System.** ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature request about: Suggest an idea for this project title: "[FEATURE REQUEST] " labels: enhancement assignees: iamolegga --- [ ] I've read [the docs](https://github.com/iamolegga/nestjs-session/blob/master/README.md) [ ] I've read [the docs of express-session](https://github.com/expressjs/session/blob/master/README.md) [ ] I couldn't find the same [feature request](https://github.com/iamolegga/nestjs-session/issues?q=is%3Aissue+label%3Aenhancement) **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. ================================================ FILE: .github/ISSUE_TEMPLATE/question.md ================================================ --- name: Question about: Please ask your question title: "[QUESTION] " labels: question assignees: iamolegga --- [ ] I've read [the docs](https://github.com/iamolegga/nestjs-session/blob/master/README.md) [ ] I've read [the docs of express-session](https://github.com/expressjs/session/blob/master/README.md) [ ] I couldn't find the same [question](https://github.com/iamolegga/nestjs-session/issues?q=is%3Aissue+label%3Aquestion) **Question** **Please mention other relevant information such as Node.js version and Operating System.** ================================================ FILE: .github/dependabot.yml ================================================ version: 2 updates: - package-ecosystem: npm directory: "/" schedule: interval: daily time: "02:00" open-pull-requests-limit: 10 ignore: - dependency-name: "reflect-metadata" update-types: ["version-update:semver-major", "version-update:semver-minor"] ================================================ FILE: .github/workflows/build-lint-test.yml ================================================ name: build-lint-test on: workflow_call: jobs: build-lint-test: strategy: fail-fast: false matrix: nestjs-version: - "8" - "9" - "10" - "11" nodejs-version: - 20 - 22 include: - nestjs-version: 8 typescript-version: 4 - nestjs-version: 9 typescript-version: 4 - nestjs-version: 10 typescript-version: 5 - nestjs-version: 11 typescript-version: 5 runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: fetch-depth: 0 - uses: actions/setup-node@v3 with: node-version: ${{ matrix.nodejs-version }} - run: npm ci - run: | npm i @nestjs/core@${{ matrix.nestjs-version }} \ @nestjs/common@${{ matrix.nestjs-version }} \ @nestjs/platform-express@${{ matrix.nestjs-version }} \ @types/node@${{ matrix.nodejs-version }} \ typescript@${{ matrix.typescript-version }} \ -D - run: npm run lint - uses: actions/cache@v3 with: path: coverage key: ${{ github.sha }}-${{ matrix.nestjs-version }}-${{ matrix.nodejs-version }} - run: npm t - run: npm run build ================================================ FILE: .github/workflows/on-pr-master.yml ================================================ name: on-pr-master on: pull_request: branches: - master jobs: build-lint-test: uses: ./.github/workflows/build-lint-test.yml secrets: inherit ================================================ FILE: .github/workflows/on-push-master.yml ================================================ name: on-push on: push: branches: - master jobs: build-lint-test: uses: ./.github/workflows/build-lint-test.yml secrets: inherit publish-alpha: if: github.actor != 'dependabot[bot]' && github.actor != 'mergify[bot]' needs: - build-lint-test uses: ./.github/workflows/publish-alpha.yml secrets: inherit coverage: needs: - build-lint-test uses: ./.github/workflows/publish-coverage.yml secrets: inherit ================================================ FILE: .github/workflows/on-release.yml ================================================ name: on-release on: release: types: [created] jobs: publish-with-git-tag-version: uses: ./.github/workflows/publish-with-git-tag-version.yml secrets: inherit ================================================ FILE: .github/workflows/publish-alpha.yml ================================================ name: publish-alpha on: workflow_call: jobs: publish-alpha: if: github.ref == 'refs/heads/master' && github.actor != 'dependabot[bot]' && github.actor != 'mergify[bot]' runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: fetch-depth: 0 - uses: actions/setup-node@v3 with: node-version: 22 registry-url: 'https://registry.npmjs.org' - run: npm ci - run: npm version --no-git-tag-version $(git describe --abbrev=0 --tags)-alpha.$(git rev-parse --short=6 ${{ github.sha }}) || true - run: npm publish --tag alpha || true env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} ================================================ FILE: .github/workflows/publish-coverage.yml ================================================ name: publish-coverage on: workflow_call: jobs: publish-coverage: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: fetch-depth: 0 - uses: actions/cache@v3 with: path: coverage # restore cache from build-lint-test wf with key=sha-(oneof nestjs version)-(oneof nodejs version) key: ${{ github.sha }}-11-22 - uses: paambaati/codeclimate-action@v2.7.5 with: coverageLocations: ${{github.workspace}}/coverage/lcov.info:lcov env: CC_TEST_REPORTER_ID: ${{ secrets.CODE_CLIMATE_REPORTER_ID }} ================================================ FILE: .github/workflows/publish-with-git-tag-version.yml ================================================ name: publish-with-git-tag-version on: workflow_call: jobs: publish-with-git-tag-version: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: fetch-depth: 0 - uses: actions/setup-node@v3 with: node-version: 22 registry-url: 'https://registry.npmjs.org' - run: npm ci - run: npm version --no-git-tag-version $(git describe --abbrev=0 --tags) - run: | git config --local user.email "github-actions[bot]@users.noreply.github.com" git config --local user.name "github-actions[bot]" git commit -m "update version" -a - uses: ad-m/github-push-action@master with: github_token: ${{ secrets.GITHUB_TOKEN }} - run: npm publish env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} ================================================ FILE: .gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* lerna-debug.log* # Diagnostic reports (https://nodejs.org/api/report.html) report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json # Runtime data pids *.pid *.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage *.lcov # nyc test coverage .nyc_output # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) bower_components # node-waf configuration .lock-wscript # Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules/ jspm_packages/ # TypeScript v1 declaration files typings/ # TypeScript cache *.tsbuildinfo # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Microbundle cache .rpt2_cache/ .rts2_cache_cjs/ .rts2_cache_es/ .rts2_cache_umd/ # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz # Yarn Integrity file .yarn-integrity # dotenv environment variables file .env .env.test # parcel-bundler cache (https://parceljs.org/) .cache # Next.js build output .next # Nuxt.js build / generate output .nuxt dist # Gatsby files .cache/ # Comment in the public line in if your project uses Gatsby and *not* Next.js # https://nextjs.org/blog/next-9-1#public-directory-support # public # vuepress build output .vuepress/dist # Serverless directories .serverless/ # FuseBox cache .fusebox/ # DynamoDB Local files .dynamodb/ # TernJS port file .tern-port ================================================ FILE: .mergify.yml ================================================ queue_rules: - name: dependabot-nestjs-session queue_conditions: - author~=^dependabot(|-preview)\[bot\]$ - -check-failure~=build-lint-test - check-success~=build-lint-test - check-success=security/snyk (iamolegga) merge_conditions: - author~=^dependabot(|-preview)\[bot\]$ - -check-failure~=build-lint-test - check-success~=build-lint-test - check-success=security/snyk (iamolegga) merge_method: rebase pull_request_rules: - name: refactored queue action rule conditions: [] actions: queue: ================================================ FILE: .prettierrc ================================================ { "singleQuote": true, "trailingComma": "all" } ================================================ FILE: .vscode/settings.json ================================================ { "typescript.tsdk": "node_modules/typescript/lib" } ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at iamolegga@gmail.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq ================================================ FILE: CONTRIBUTING.md ================================================ All pull requests that respect next rules are welcome: - Before opening pull request to this repo run `npm t` to run tests. - All bugfixes and features should contain tests and coverage must be 100% ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2019 iamolegga Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================

NestJS-Session

npm npm GitHub branch checks state Known Vulnerabilities Libraries.io Dependabot Supported platforms: Express

Idiomatic Session Module for NestJS. Built on top of express-session 😎

This module implements a session with storing data in one of [external stores](https://github.com/expressjs/session#compatible-session-stores) and passing ID of session to client via `Cookie`/`Set-Cookie` headers. If you want to store data directly in `Cookie`, you can look at [nestjs-cookie-session](https://github.com/iamolegga/nestjs-cookie-session). ## Example Register module: ```ts // app.module.ts import { Module } from '@nestjs/common'; import { NestSessionOptions, SessionModule } from 'nestjs-session'; import { ViewsController } from './views.controller'; @Module({ imports: [ // sync params: SessionModule.forRoot({ session: { secret: 'keyboard cat' }, }), // or async: SessionModule.forRootAsync({ imports: [ConfigModule], inject: [Config], // TIP: to get autocomplete in return object // add `NestSessionOptions` here ↓↓↓ useFactory: async (config: Config): Promise => { return { session: { secret: config.secret }, }; }, }), ], controllers: [ViewsController], }) export class AppModule {} ``` In controllers use NestJS built-in `Session` decorator: ```ts // views.controller.ts import { Controller, Get, Session } from '@nestjs/common'; @Controller('views') export class ViewsController { @Get() getViews(@Session() session: { views?: number }) { session.views = (session.views || 0) + 1; return session.views; } } ``` --- **BE AWARE THAT THIS EXAMPLE IS NOT FOR PRODUCTION! IT USES IN-MEMORY STORE, SO YOUR DATA WILL BE LOST ON RESTART. USE OTHER [STORES](https://github.com/expressjs/session#compatible-session-stores)** --- See [redis-store](https://github.com/tj/connect-redis) example in `examples` folder. To run examples: ```sh git clone https://github.com/iamolegga/nestjs-session.git cd nestjs-session npm i npm run build cd examples/in-memory # or `cd examples/redis-store` npm i npm start ``` For Redis example, you should start Redis on localhost:6379. If you have Docker installed you can start Redis image by `npm run redis` from `redis-store` directory. ## Install ```sh npm i nestjs-session express-session @types/express-session ``` ## API ### SessionModule `SessionModule` class has two static methods, that returns `DynamicModule`, that you need to import: - `SessionModule.forRoot` for sync configuration without dependencies - `SessionModule.forRootAsync` for sync/async configuration with dependencies ### SessionModule.forRoot Accept `NestSessionOptions`. Returns NestJS `DynamicModule` for import. ### SessionModule.forRootAsync Accept `NestSessionAsyncOptions`. Returns NestJS `DynamicModule` for import. ### NestSessionOptions `NestSessionOptions` is the interface of all options. It has next properties: - `session` - **required** - [express-session options](https://github.com/expressjs/session#options). - `forRoutes` - **optional** - same as NestJS buil-in `MiddlewareConfigProxy['forRoutes']` [See examples in official docs](https://docs.nestjs.com/middleware#applying-middleware). Specify routes, that should have access to session. If `forRoutes` and `exclude` will not be set, then sessions will be set to all routes. - `exclude` - **optional** - same as NestJS buil-in `MiddlewareConfigProxy['exclude']` [See examples in official docs](https://docs.nestjs.com/middleware#applying-middleware). Specify routes, that should not have access to session. If `forRoutes` and `exclude` will not be set, then sessions will be set to all routes. - `retries` - **optional** - `number` - by default if your session store lost connection to database it will return session as `undefined`, and no errors will be thrown, and then you need to check session in controller. But you can set this property how many times it should retry to get session, and on fail `InternalServerErrorException` will be thrown. If you don't want retries, but just want to `InternalServerErrorException` to be throw, then set to `0`. Set this option, if you dont't want manualy check session inside controllers. - `retriesStrategy` - **optional** - `(attempt: number) => number` - function that returns number of ms to wait between next attempt. Not calls on first attempt. ### NestSessionAsyncOptions `NestSessionAsyncOptions` is the interface of options to create session module, that depends on other modules. It has next properties: - `imports` - **optional** - modules, that session module depends on. See [official docs](https://docs.nestjs.com/modules). - `inject` - **optional** - providers from `imports`-property modules, that will be passed as arguments to `useFactory` method. - `useFactory` - **required** - method, that returns `NestSessionOptions`. ## Migration ### v2 `express-session` and `@types/express-session` are moved to peer dependencies, so you can update them independently.

Do you use this library?
Don't be shy to give it a star! ★

Also if you are into NestJS you might be interested in one of my other NestJS libs.

================================================ FILE: __tests__/forRoot.spec.ts ================================================ import { Controller, Get, Module, Session } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { SessionModule } from '../src'; import { platforms } from './utils/platforms'; import { doubleRequest } from './utils/request'; describe(SessionModule.forRoot.name, () => { for (const PlatformAdapter of platforms) { describe(PlatformAdapter.name, () => { it('works', async () => { @Controller('/') class TestController { @Get() get(@Session() session?: { views?: number }) { if (!session) { return { views: 0 }; } session.views = (session.views || 0) + 1; return { views: session.views }; } } @Module({ imports: [SessionModule.forRoot({ session: { secret: 'test' } })], controllers: [TestController], }) class TestModule {} const app = await NestFactory.create( TestModule, new PlatformAdapter(), { logger: false }, ); const server = app.getHttpServer(); await app.init(); const [res1, res2] = await doubleRequest(server); await app.close(); expect(res1.body.views).toBe(1); expect(res2.body.views).toBe(2); }); }); } }); ================================================ FILE: __tests__/forRootAsync.spec.ts ================================================ import { Controller, Get, Module, Session } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { NestSessionOptions, SessionModule } from '../src'; import { platforms } from './utils/platforms'; import { doubleRequest } from './utils/request'; describe(SessionModule.forRootAsync.name, () => { for (const PlatformAdapter of platforms) { describe(PlatformAdapter.name, () => { it('works', async () => { @Controller('/') class TestController { @Get() get(@Session() session?: { views?: number }) { if (!session) { return { views: 0 }; } session.views = (session.views || 0) + 1; return { views: session.views }; } } @Module({ imports: [ SessionModule.forRootAsync({ useFactory: (): | NestSessionOptions | Promise => ({ session: { secret: 'test' }, }), }), ], controllers: [TestController], }) class TestModule {} const app = await NestFactory.create( TestModule, new PlatformAdapter(), { logger: false }, ); const server = app.getHttpServer(); await app.init(); const [res1, res2] = await doubleRequest(server); await app.close(); expect(res1.body.views).toBe(1); expect(res2.body.views).toBe(2); }); }); } }); ================================================ FILE: __tests__/retires.spec.ts ================================================ import { Controller, Get, Module, Session } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { Handler } from 'express'; import { MemoryStore } from 'express-session'; import request from 'supertest'; import { SessionModule } from '../src'; import { platforms } from './utils/platforms'; import { doubleRequest } from './utils/request'; describe('retries', () => { for (const PlatformAdapter of platforms) { describe(PlatformAdapter.name, () => { it('session is undefined with disconnected store', async () => { @Controller('/') class TestController { @Get() get(@Session() session?: { views?: number }) { return { sessionType: typeof session }; } } const store = new MemoryStore(); @Module({ imports: [ SessionModule.forRoot({ session: { secret: 'test', store } }), ], controllers: [TestController], }) class TestModule {} const app = await NestFactory.create( TestModule, new PlatformAdapter(), { logger: false }, ); const server = app.getHttpServer(); await app.init(); store.emit('disconnect'); const result = await request(server).get('/'); await app.close(); expect(result.body).toEqual({ sessionType: 'undefined' }); }); it('controllers should be blocked with disconnected store and set retries', async () => { let isControllerCalled = false; @Controller('/') class TestController { @Get() get() { isControllerCalled = true; } } const store = new MemoryStore(); @Module({ imports: [ SessionModule.forRoot({ session: { secret: 'test', store }, retries: 0, }), ], controllers: [TestController], }) class TestModule {} const app = await NestFactory.create( TestModule, new PlatformAdapter(), { logger: false }, ); const server = app.getHttpServer(); await app.init(); store.emit('disconnect'); const result = await request(server).get('/'); await app.close(); expect(result.status).toBe(500); expect(isControllerCalled).toBeFalsy(); }); it('retries should work when reconnected', async () => { let isControllerCalled = false; @Controller('/') class TestController { @Get() get() { isControllerCalled = true; } } const store = new MemoryStore(); @Module({ imports: [ SessionModule.forRoot({ session: { secret: 'test', store }, retries: 1, }), ], controllers: [TestController], }) class TestModule {} const app = await NestFactory.create( TestModule, new PlatformAdapter(), { logger: false }, ); app.use(((_req, _res, next) => { next(); process.nextTick(() => { store.emit('connect'); }); }) as Handler); const server = app.getHttpServer(); await app.init(); store.emit('disconnect'); const reqPromise = request(server).get('/'); const result = await reqPromise; await app.close(); expect(result.status).toBe(200); expect(isControllerCalled).toBeTruthy(); }); it('controllers should be blocked with error in store and set retries', async () => { let callTimes = 0; @Controller('/') class TestController { @Get() get() { callTimes++; } } const store = new MemoryStore(); store.get = (_sid, cb) => cb(new Error()); @Module({ imports: [ SessionModule.forRoot({ session: { secret: 'test', store }, retries: 0, }), ], controllers: [TestController], }) class TestModule {} const app = await NestFactory.create( TestModule, new PlatformAdapter(), { logger: false }, ); const server = app.getHttpServer(); await app.init(); const [, result] = await doubleRequest(server); await app.close(); expect(result.status).toBe(500); expect(callTimes).toBe(1); }); }); } }); ================================================ FILE: __tests__/routing.spec.ts ================================================ import { Controller, Get, Module, RequestMethod, Session, } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { SessionModule } from '../src'; import { platforms } from './utils/platforms'; import { doubleRequest } from './utils/request'; describe('routing', () => { for (const PlatformAdapter of platforms) { describe(PlatformAdapter.name, () => { it('forRoutes', async () => { @Controller('/') class TestController { @Get('with-session') withSession(@Session() session?: { views?: number }) { if (!session) { return { views: 1 }; } session.views = (session.views || 0) + 1; return { views: session.views }; } @Get('without-session') withoutSession(@Session() session?: { views?: number }) { if (!session) { return { views: 1 }; } session.views = (session.views || 0) + 1; return { views: session.views }; } } @Module({ imports: [ SessionModule.forRoot({ session: { secret: 'test' }, forRoutes: [{ method: RequestMethod.ALL, path: 'with-session' }], }), ], controllers: [TestController], }) class TestModule {} const app = await NestFactory.create( TestModule, new PlatformAdapter(), { logger: false }, ); const server = app.getHttpServer(); await app.init(); const [sessRes1, sessRes2] = await doubleRequest( server, '/with-session', ); const [noSessRes1, noSessRes2] = await doubleRequest( server, '/without-session', ); await app.close(); expect(sessRes1.body.views).toBe(1); expect(sessRes2.body.views).toBe(2); expect(noSessRes1.body.views).toBe(1); expect(noSessRes2.body.views).toBe(1); }); it('exclude', async () => { @Controller('/') class TestController { @Get('with-session') withSession(@Session() session?: { views?: number }) { if (!session) { return { views: 1 }; } session.views = (session.views || 0) + 1; return { views: session.views }; } @Get('without-session') withoutSession(@Session() session?: { views?: number }) { if (!session) { return { views: 1 }; } session.views = (session.views || 0) + 1; return { views: session.views }; } } @Module({ imports: [ SessionModule.forRoot({ session: { secret: 'test' }, exclude: [{ method: RequestMethod.ALL, path: 'without-session' }], forRoutes: [TestController], }), ], controllers: [TestController], }) class TestModule {} const app = await NestFactory.create( TestModule, new PlatformAdapter(), { logger: false }, ); const server = app.getHttpServer(); await app.init(); const [sessRes1, sessRes2] = await doubleRequest( server, '/with-session', ); const [noSessRes1, noSessRes2] = await doubleRequest( server, '/without-session', ); await app.close(); expect(sessRes1.body.views).toBe(1); expect(sessRes2.body.views).toBe(2); expect(noSessRes1.body.views).toBe(1); expect(noSessRes2.body.views).toBe(1); }); }); } }); ================================================ FILE: __tests__/utils/platforms.ts ================================================ import { Type } from '@nestjs/common'; import { AbstractHttpAdapter } from '@nestjs/core'; import { ExpressAdapter } from '@nestjs/platform-express'; // eslint-disable-next-line @typescript-eslint/no-explicit-any export type Adapter = Type>; export const platforms: Adapter[] = [ExpressAdapter]; ================================================ FILE: __tests__/utils/request.ts ================================================ import request from 'supertest'; export async function doubleRequest( server: Parameters[0], path = '/', ) { const result1 = await request(server).get(path); const cookie = result1.header['set-cookie']; const result2 = await request(server) .get(path) .set('Cookie', cookie ? [cookie] : []); return [result1, result2] as [request.Response, request.Response]; } ================================================ FILE: eslint.config.cjs ================================================ const { fixupConfigRules, fixupPluginRules } = require('@eslint/compat'); const { FlatCompat } = require('@eslint/eslintrc'); const js = require('@eslint/js'); const typescriptEslintEslintPlugin = require('@typescript-eslint/eslint-plugin'); const tsParser = require('@typescript-eslint/parser'); const globals = require('globals'); const compat = new FlatCompat({ baseDirectory: __dirname, recommendedConfig: js.configs.recommended, allConfig: js.configs.all, }); module.exports = [ { ignores: ['eslint.config.cjs'], }, ...fixupConfigRules( compat.extends( 'plugin:@typescript-eslint/recommended', 'plugin:import/recommended', 'plugin:import/typescript', 'plugin:prettier/recommended', ), ), { plugins: { '@typescript-eslint': fixupPluginRules(typescriptEslintEslintPlugin), }, languageOptions: { globals: { ...globals.node, ...globals.jest, }, parser: tsParser, ecmaVersion: 5, sourceType: 'module', parserOptions: { project: 'tsconfig.json', }, }, rules: { '@typescript-eslint/no-explicit-any': [ 'error', { fixToUnknown: true, ignoreRestArgs: false, }, ], '@typescript-eslint/no-floating-promises': [ 'error', { ignoreIIFE: true, }, ], '@typescript-eslint/no-unused-vars': [ 'error', { varsIgnorePattern: '^_', argsIgnorePattern: '^_', ignoreRestSiblings: true, }, ], '@typescript-eslint/explicit-member-accessibility': [ 'error', { accessibility: 'no-public', }, ], '@typescript-eslint/member-ordering': [ 'error', { default: [ 'public-static-field', 'public-static-get', 'public-static-set', 'public-static-method', 'protected-static-field', 'protected-static-get', 'protected-static-set', 'protected-static-method', 'private-static-field', 'private-static-get', 'private-static-set', 'private-static-method', 'signature', 'public-abstract-field', 'protected-abstract-field', 'public-decorated-field', 'public-instance-field', 'protected-decorated-field', 'protected-instance-field', 'private-decorated-field', 'private-instance-field', 'public-constructor', 'protected-constructor', 'private-constructor', 'public-abstract-get', 'public-abstract-set', 'public-abstract-method', 'public-decorated-get', 'public-instance-get', 'public-decorated-set', 'public-instance-set', 'public-decorated-method', 'public-instance-method', 'protected-abstract-get', 'protected-abstract-set', 'protected-abstract-method', 'protected-decorated-get', 'protected-instance-get', 'protected-decorated-set', 'protected-instance-set', 'protected-decorated-method', 'protected-instance-method', 'private-decorated-get', 'private-instance-get', 'private-decorated-set', 'private-instance-set', 'private-decorated-method', 'private-instance-method', ], }, ], 'import/order': [ 'error', { alphabetize: { order: 'asc', caseInsensitive: true, }, 'newlines-between': 'always', }, ], }, }, ]; ================================================ FILE: examples/in-memory/.eslintrc.js ================================================ module.exports = { parser: '@typescript-eslint/parser', parserOptions: { project: 'tsconfig.json', sourceType: 'module', }, plugins: ['@typescript-eslint/eslint-plugin'], extends: [ 'plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended', ], root: true, env: { node: true, jest: true, }, ignorePatterns: ['.eslintrc.js'], rules: { '@typescript-eslint/interface-name-prefix': 'off', '@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/explicit-module-boundary-types': 'off', '@typescript-eslint/no-explicit-any': 'off', }, }; ================================================ FILE: examples/in-memory/.gitignore ================================================ # compiled output /dist /node_modules # Logs logs *.log npm-debug.log* pnpm-debug.log* yarn-debug.log* yarn-error.log* lerna-debug.log* # OS .DS_Store # Tests /coverage /.nyc_output # IDEs and editors /.idea .project .classpath .c9/ *.launch .settings/ *.sublime-workspace # IDE - VSCode .vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json ================================================ FILE: examples/in-memory/.prettierrc ================================================ { "singleQuote": true, "trailingComma": "all" } ================================================ FILE: examples/in-memory/README.md ================================================

Nest Logo

[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456 [circleci-url]: https://circleci.com/gh/nestjs/nest

A progressive Node.js framework for building efficient and scalable server-side applications.

NPM Version Package License NPM Downloads CircleCI Coverage Discord Backers on Open Collective Sponsors on Open Collective Support us

## Description [Nest](https://github.com/nestjs/nest) framework TypeScript starter repository. ## Installation ```bash $ npm install ``` ## Running the app ```bash # development $ npm run start # watch mode $ npm run start:dev # production mode $ npm run start:prod ``` ## Test ```bash # unit tests $ npm run test # e2e tests $ npm run test:e2e # test coverage $ npm run test:cov ``` ## Support Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support). ## Stay in touch - Author - [Kamil Myśliwiec](https://kamilmysliwiec.com) - Website - [https://nestjs.com](https://nestjs.com/) - Twitter - [@nestframework](https://twitter.com/nestframework) ## License Nest is [MIT licensed](LICENSE). ================================================ FILE: examples/in-memory/nest-cli.json ================================================ { "collection": "@nestjs/schematics", "sourceRoot": "src" } ================================================ FILE: examples/in-memory/package.json ================================================ { "name": "in-memory", "version": "0.0.1", "description": "", "author": "", "private": true, "license": "UNLICENSED", "scripts": { "prebuild": "rimraf dist", "build": "nest build", "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", "start": "nest start", "start:dev": "nest start --watch", "start:debug": "nest start --debug --watch", "start:prod": "node dist/main", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "test": "jest", "test:watch": "jest --watch", "test:cov": "jest --coverage", "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", "test:e2e": "jest --config ./test/jest-e2e.json" }, "dependencies": { "@nestjs/common": "^11.0.16", "@nestjs/core": "^11.1.18", "@nestjs/platform-express": "^11.1.19", "@types/express-session": "^1.17.4", "express-session": "^1.18.2", "reflect-metadata": "^0.1.13", "rimraf": "^3.0.2", "rxjs": "^7.2.0" }, "devDependencies": { "@nestjs/cli": "^11.0.16", "@nestjs/schematics": "^8.0.0", "@nestjs/testing": "^11.0.16", "@types/express": "^4.17.13", "@types/jest": "^27.0.1", "@types/node": "^16.0.0", "@types/supertest": "^2.0.11", "@typescript-eslint/eslint-plugin": "^4.28.2", "@typescript-eslint/parser": "^4.28.2", "eslint": "^7.30.0", "eslint-config-prettier": "^8.3.0", "eslint-plugin-prettier": "^3.4.0", "jest": "^30.2.0", "prettier": "^2.3.2", "supertest": "^7.0.0", "ts-jest": "^27.0.3", "ts-loader": "^9.2.3", "ts-node": "^10.0.0", "tsconfig-paths": "^3.14.1", "typescript": "^4.3.5" }, "jest": { "moduleFileExtensions": [ "js", "json", "ts" ], "rootDir": "src", "testRegex": ".*\\.spec\\.ts$", "transform": { "^.+\\.(t|j)s$": "ts-jest" }, "collectCoverageFrom": [ "**/*.(t|j)s" ], "coverageDirectory": "../coverage", "testEnvironment": "node" } } ================================================ FILE: examples/in-memory/src/app.controller.ts ================================================ import { Controller, Get, Session } from '@nestjs/common'; @Controller() export class AppController { @Get() getHello(@Session() session: { views?: number }) { session.views = (session.views || 0) + 1; return session.views; } } ================================================ FILE: examples/in-memory/src/app.module.ts ================================================ import { Module } from '@nestjs/common'; import { SessionModule } from '../../../dist'; import { AppController } from './app.controller'; @Module({ imports: [ SessionModule.forRoot({ session: { secret: 'qwerty' }, }), ], controllers: [AppController], }) export class AppModule {} ================================================ FILE: examples/in-memory/src/main.ts ================================================ import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); } bootstrap(); ================================================ FILE: examples/in-memory/tsconfig.build.json ================================================ { "extends": "./tsconfig.json", "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] } ================================================ FILE: examples/in-memory/tsconfig.json ================================================ { "compilerOptions": { "module": "commonjs", "declaration": true, "removeComments": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "allowSyntheticDefaultImports": true, "target": "es2017", "sourceMap": true, "outDir": "./dist", "baseUrl": "./", "incremental": true, "skipLibCheck": true, "strictNullChecks": false, "noImplicitAny": false, "strictBindCallApply": false, "forceConsistentCasingInFileNames": false, "noFallthroughCasesInSwitch": false } } ================================================ FILE: examples/redis-store/.eslintrc.js ================================================ module.exports = { parser: '@typescript-eslint/parser', parserOptions: { project: 'tsconfig.json', sourceType: 'module', }, plugins: ['@typescript-eslint/eslint-plugin'], extends: [ 'plugin:@typescript-eslint/recommended', 'plugin:prettier/recommended', ], root: true, env: { node: true, jest: true, }, ignorePatterns: ['.eslintrc.js'], rules: { '@typescript-eslint/interface-name-prefix': 'off', '@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/explicit-module-boundary-types': 'off', '@typescript-eslint/no-explicit-any': 'off', }, }; ================================================ FILE: examples/redis-store/.gitignore ================================================ # compiled output /dist /node_modules # Logs logs *.log npm-debug.log* pnpm-debug.log* yarn-debug.log* yarn-error.log* lerna-debug.log* # OS .DS_Store # Tests /coverage /.nyc_output # IDEs and editors /.idea .project .classpath .c9/ *.launch .settings/ *.sublime-workspace # IDE - VSCode .vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json ================================================ FILE: examples/redis-store/.prettierrc ================================================ { "singleQuote": true, "trailingComma": "all" } ================================================ FILE: examples/redis-store/README.md ================================================

Nest Logo

[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456 [circleci-url]: https://circleci.com/gh/nestjs/nest

A progressive Node.js framework for building efficient and scalable server-side applications.

NPM Version Package License NPM Downloads CircleCI Coverage Discord Backers on Open Collective Sponsors on Open Collective Support us

## Description [Nest](https://github.com/nestjs/nest) framework TypeScript starter repository. ## Installation ```bash $ npm install ``` ## Running the app ```bash # development $ npm run start # watch mode $ npm run start:dev # production mode $ npm run start:prod ``` ## Test ```bash # unit tests $ npm run test # e2e tests $ npm run test:e2e # test coverage $ npm run test:cov ``` ## Support Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support). ## Stay in touch - Author - [Kamil Myśliwiec](https://kamilmysliwiec.com) - Website - [https://nestjs.com](https://nestjs.com/) - Twitter - [@nestframework](https://twitter.com/nestframework) ## License Nest is [MIT licensed](LICENSE). ================================================ FILE: examples/redis-store/nest-cli.json ================================================ { "collection": "@nestjs/schematics", "sourceRoot": "src" } ================================================ FILE: examples/redis-store/package.json ================================================ { "name": "redis-store", "version": "0.0.1", "description": "", "author": "", "private": true, "license": "UNLICENSED", "scripts": { "prebuild": "rimraf dist", "build": "nest build", "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", "start": "nest start", "start:dev": "nest start --watch", "start:debug": "nest start --debug --watch", "start:prod": "node dist/main", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "test": "jest", "test:watch": "jest --watch", "test:cov": "jest --coverage", "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", "test:e2e": "jest --config ./test/jest-e2e.json", "redis": "docker run -p 6379:6379 redis" }, "dependencies": { "@nestjs/common": "^11.0.16", "@nestjs/core": "^11.1.18", "@nestjs/platform-express": "^11.1.16", "@types/connect-redis": "^0.0.17", "@types/express-session": "^1.17.4", "connect-redis": "^6.0.0", "express-session": "^1.18.2", "nestjs-redis": "^1.3.3", "reflect-metadata": "^0.1.13", "rimraf": "^3.0.2", "rxjs": "^7.2.0" }, "devDependencies": { "@nestjs/cli": "^11.0.16", "@nestjs/schematics": "^8.0.0", "@nestjs/testing": "^11.1.13", "@types/express": "^4.17.13", "@types/jest": "^27.0.1", "@types/node": "^16.0.0", "@types/supertest": "^2.0.11", "@typescript-eslint/eslint-plugin": "^4.28.2", "@typescript-eslint/parser": "^4.28.2", "eslint": "^7.30.0", "eslint-config-prettier": "^8.3.0", "eslint-plugin-prettier": "^3.4.0", "jest": "^30.2.0", "prettier": "^2.3.2", "supertest": "^7.0.0", "ts-jest": "^27.0.3", "ts-loader": "^9.2.3", "ts-node": "^10.0.0", "tsconfig-paths": "^3.14.1", "typescript": "^4.3.5" }, "jest": { "moduleFileExtensions": [ "js", "json", "ts" ], "rootDir": "src", "testRegex": ".*\\.spec\\.ts$", "transform": { "^.+\\.(t|j)s$": "ts-jest" }, "collectCoverageFrom": [ "**/*.(t|j)s" ], "coverageDirectory": "../coverage", "testEnvironment": "node" } } ================================================ FILE: examples/redis-store/src/app.controller.ts ================================================ import { Controller, Get, Session } from '@nestjs/common'; @Controller() export class AppController { @Get() getHello(@Session() session: { views?: number }) { session.views = (session.views || 0) + 1; return session.views; } } ================================================ FILE: examples/redis-store/src/app.module.ts ================================================ import { Module } from '@nestjs/common'; import { AppController } from './app.controller'; import { Session } from './session.module'; @Module({ imports: [Session], controllers: [AppController], }) export class AppModule {} ================================================ FILE: examples/redis-store/src/config.module.ts ================================================ import { Module } from '@nestjs/common'; import { ConfigService } from './config.service'; @Module({ providers: [ConfigService], exports: [ConfigService], }) export class ConfigModule {} ================================================ FILE: examples/redis-store/src/config.service.ts ================================================ import { Injectable } from '@nestjs/common'; @Injectable() export class ConfigService { public readonly REDIS_PORT = Number(process.env.REDIS_PORT || 6379); public readonly REDIS_HOST = process.env.REDIS_HOST; public readonly SESSION_SECRET = process.env.SESSION_SECRET || 'supersecret'; } ================================================ FILE: examples/redis-store/src/main.ts ================================================ import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); } bootstrap(); ================================================ FILE: examples/redis-store/src/redis.module.ts ================================================ import { DynamicModule } from '@nestjs/common'; import { RedisModule, RedisModuleOptions } from 'nestjs-redis'; import { ConfigModule } from './config.module'; import { ConfigService } from './config.service'; export const Redis: DynamicModule = RedisModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: (config: ConfigService): RedisModuleOptions => { return { host: config.REDIS_HOST, port: config.REDIS_PORT, }; }, }); ================================================ FILE: examples/redis-store/src/session.module.ts ================================================ import * as ConnectRedis from 'connect-redis'; import * as session from 'express-session'; import { RedisService } from 'nestjs-redis'; import { NestSessionOptions, SessionModule } from '../../../dist'; import { ConfigModule } from './config.module'; import { ConfigService } from './config.service'; import { Redis } from './redis.module'; const RedisStore = ConnectRedis(session); export const Session = SessionModule.forRootAsync({ imports: [Redis, ConfigModule], inject: [RedisService, ConfigService], useFactory: ( redisService: RedisService, config: ConfigService, ): NestSessionOptions => { const redisClient = redisService.getClient(); const store = new RedisStore({ client: redisClient as any }); return { session: { store, secret: config.SESSION_SECRET, }, }; }, }); ================================================ FILE: examples/redis-store/tsconfig.build.json ================================================ { "extends": "./tsconfig.json", "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] } ================================================ FILE: examples/redis-store/tsconfig.json ================================================ { "compilerOptions": { "module": "commonjs", "declaration": true, "removeComments": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "allowSyntheticDefaultImports": true, "target": "es2017", "sourceMap": true, "outDir": "./dist", "baseUrl": "./", "incremental": true, "skipLibCheck": true, "strictNullChecks": false, "noImplicitAny": false, "strictBindCallApply": false, "forceConsistentCasingInFileNames": false, "noFallthroughCasesInSwitch": false } } ================================================ FILE: jest.config.js ================================================ module.exports = { moduleFileExtensions: ['js', 'ts'], testRegex: '.spec.ts$', transform: { '^.+\\.(t|j)s$': 'ts-jest', }, collectCoverage: true, coverageDirectory: './coverage', collectCoverageFrom: ['src/**/*.ts'], testEnvironment: 'node', setupFiles: [], }; ================================================ FILE: package.json ================================================ { "name": "nestjs-session", "version": "4.0.0", "description": "Idiomatic NestJS module for session", "main": "index.js", "typings": "index.d.ts", "scripts": { "test": "jest --verbose -i --detectOpenHandles", "lint": "tsc --noemit && eslint \"{src,__tests__}/**/*.ts\" --fix", "prebuild": "rimraf dist", "build": "tsc -p tsconfig.build.json", "prepublishOnly": "npm run build && cp -r ./dist/* .", "postpublish": "git clean -fd" }, "files": [ "*.{js,d.ts}", "!jest.config.js", "!.eslintrc.js" ], "engineStrict": true, "engines": { "node": ">=18.0.0" }, "repository": { "type": "git", "url": "git+https://github.com/iamolegga/nestjs-session.git" }, "keywords": [ "nestjs", "nest.js", "nest", "session", "express", "express-session" ], "author": "iamolegga (http://github.com/iamolegga)", "license": "MIT", "bugs": { "url": "https://github.com/iamolegga/nestjs-session/issues" }, "homepage": "https://github.com/iamolegga/nestjs-session#readme", "dependencies": { "create-nestjs-middleware-module": "^0.4.0" }, "devDependencies": { "@eslint/compat": "^2.0.0", "@eslint/eslintrc": "^3.2.0", "@eslint/js": "^9.18.0", "@nestjs/common": "^11.0.4", "@nestjs/core": "^11.0.4", "@nestjs/platform-express": "^11.0.4", "@types/express-session": "^1.18.1", "@types/jest": "^29.5.14", "@types/node": "^25.0.0", "@types/supertest": "^7.2.0", "@typescript-eslint/eslint-plugin": "^8.21.0", "@typescript-eslint/parser": "^8.21.0", "eslint": "^9.18.0", "eslint-config-prettier": "^10.0.1", "eslint-plugin-import": "^2.31.0", "eslint-plugin-prettier": "^5.2.3", "express-session": "^1.18.1", "jest": "30.0.0", "prettier": "^3.4.2", "reflect-metadata": "^0.1.14", "rimraf": "^6.0.1", "rxjs": "^7.8.1", "supertest": "^7.0.0", "ts-jest": "^29.2.5", "ts-loader": "^9.5.2", "ts-node": "^10.9.2", "typescript": "^6.0.2" }, "peerDependencies": { "@types/express-session": "^1.17.4", "express-session": "^1.17.2" } } ================================================ FILE: src/index.ts ================================================ import { AsyncOptions, createModule, SyncOptions, } from 'create-nestjs-middleware-module'; import expressSession from 'express-session'; import { createRetriesMiddleware } from './retriesMiddleware'; interface Options { /** * express-session options. @see https://github.com/expressjs/session#options */ session: expressSession.SessionOptions; /** * by default if your session store lost connection to database it will return * session as `undefined`, and no errors will be thrown, and then you need to * check session in controller. But you can set this property how many times * it should retry to get session, and on fail `InternalServerErrorException` * will be thrown. If you don't want retries, but just want to * `InternalServerErrorException` to be throw, then set to `0`. Set this * option, if you dont't want manualy check session inside controllers. */ retries?: number; /** * function that returns number of ms to wait between next attempt. Not calls * on first attempt. */ retriesStrategy?: Parameters[2]; } export type NestSessionOptions = SyncOptions; export type NestSessionAsyncOptions = AsyncOptions; export const SessionModule = createModule((options) => { const { retries, session, retriesStrategy } = options; let middleware = expressSession(session); if (retries !== undefined) { middleware = createRetriesMiddleware(middleware, retries, retriesStrategy); } return middleware; }); ================================================ FILE: src/retriesMiddleware.ts ================================================ import { InternalServerErrorException } from '@nestjs/common'; import * as express from 'express'; type WaitingStrategy = (attempt: number) => number; export function createRetriesMiddleware( sessionMiddleware: express.RequestHandler, retries: number, retiesStrategy: WaitingStrategy = () => 0, ): express.RequestHandler { return async (req, res, next) => { let attempt = 0; async function lookupSession(error?: unknown) { if (error) { return next(error); } if (req.session !== undefined) { return next(); } if (attempt > retries) { return next(new InternalServerErrorException('Cannot create session')); } if (attempt !== 0) { await new Promise((r) => setTimeout(r, retiesStrategy(attempt))); } attempt++; sessionMiddleware(req, res, lookupSession); } await lookupSession(); }; } ================================================ FILE: tsconfig.build.json ================================================ { "extends": "./tsconfig.json", "exclude": ["node_modules", "dist", "__tests__", "examples"] } ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { "lib": ["ES2022"], "module": "node16", "target": "ES2022", "removeComments": false, "emitDecoratorMetadata": true, "experimentalDecorators": true, "allowSyntheticDefaultImports": true, "resolveJsonModule": true, "esModuleInterop": true, "sourceMap": true, "outDir": "./dist", "incremental": true, "skipLibCheck": true, "strict": true, "noUncheckedIndexedAccess": true, "typeRoots": ["src/typings", "node_modules/@types"], "declaration": true }, "exclude": ["examples"] }