All Projects → iamolegga → nestjs-session

iamolegga / nestjs-session

Licence: MIT license
Idiomatic Session Module for NestJS. Built on top of `express-session` 😎

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to nestjs-session

nestjs-cookie-session
Idiomatic Cookie Session Module for NestJS. Built on top of `cookie-session` 😻
Stars: ✭ 35 (-76.67%)
Mutual labels:  expressjs, session, nest, nestjs
nestjs-ratelimiter
Distributed consistent flexible NestJS rate limiter based on Redis
Stars: ✭ 49 (-67.33%)
Mutual labels:  nest, nestjs
MyAPI
A template to create awesome APIs easily ⚡️
Stars: ✭ 117 (-22%)
Mutual labels:  nest, nestjs
typegraphql-nestjs
TypeGraphQL integration with NestJS
Stars: ✭ 117 (-22%)
Mutual labels:  nest, nestjs
Cookie Session
Simple cookie-based session middleware
Stars: ✭ 928 (+518.67%)
Mutual labels:  expressjs, session
Builderbook
Open source web application to learn JS stack: React, Material-UI, Next.js, Node.js, Express.js, Mongoose, MongoDB database.
Stars: ✭ 3,015 (+1910%)
Mutual labels:  expressjs, express-session
nest-queue
Queue manager for NestJS Framework for Redis (via bull package)
Stars: ✭ 69 (-54%)
Mutual labels:  nest, nestjs
nestjs-asyncapi
NestJS AsyncAPI module - generate the documentation of your event-based services using decorators
Stars: ✭ 88 (-41.33%)
Mutual labels:  nest, nestjs
prime-nestjs
A production-ready NestJS boilerplate using Typescript, Postgres, TypeORM, and Docker.
Stars: ✭ 140 (-6.67%)
Mutual labels:  nest, nestjs
nestjs-telegraf
🤖 Powerful Nest module for easy and fast creation Telegram bots
Stars: ✭ 300 (+100%)
Mutual labels:  nest, nestjs
nestjs-starter
🚀 Nest framework starter
Stars: ✭ 30 (-80%)
Mutual labels:  nest, nestjs
in-memory-db
Simple In-Memory DB Service for NestJS projects
Stars: ✭ 55 (-63.33%)
Mutual labels:  expressjs, nestjs
Session
Simple session middleware for Express
Stars: ✭ 5,571 (+3614%)
Mutual labels:  expressjs, session
Nest Mean
NestJS Tutorial Repository
Stars: ✭ 250 (+66.67%)
Mutual labels:  expressjs, nestjs
Books-Library-API
A starter template for building a restful API with nestjs, nodejs , expressjs , monogdb, mongoose
Stars: ✭ 21 (-86%)
Mutual labels:  expressjs, nestjs
twitch-project
A weekly stream in which I build a web application with Neo4j and Typescript
Stars: ✭ 78 (-48%)
Mutual labels:  nest, nestjs
ng-nest-cnode
Angular 10 Front-End and Nestjs 7 framework Back-End build Fullstack CNode
Stars: ✭ 17 (-88.67%)
Mutual labels:  expressjs, nestjs
postgres-nest-react-typescript-boilerplate
No description or website provided.
Stars: ✭ 93 (-38%)
Mutual labels:  expressjs, nestjs
nestjs-objection
Objection module for NestJS
Stars: ✭ 24 (-84%)
Mutual labels:  nest, nestjs
bundled-nest
💥 Nest 🔰 Webpack 🔰 Docker 💥 --- 🏯 Now archived for historical reference ⛩
Stars: ✭ 59 (-60.67%)
Mutual labels:  nest, nestjs

NestJS-Session

npm GitHub branch checks state Supported platforms: Express

Snyk Vulnerabilities for npm package Dependencies status Dependabot Maintainability

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

This module implements a session with storing data in one of external 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.

Example

Register module:

// 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<NestSessionOptions> => {
        return {
          session: { secret: config.secret },
        };
      },
    }),
  ],
  controllers: [ViewsController],
})
export class AppModule {}

In controllers use NestJS built-in Session decorator:

// 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


See redis-store example in examples folder.

To run examples:

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

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.
  • forRoutes - optional - same as NestJS buil-in MiddlewareConfigProxy['forRoutes'] See examples in official docs. 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. 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.
  • 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 ecosystem you may be interested in one of my other libs:

nestjs-pino

GitHub stars npm

Platform agnostic logger for NestJS based on pino with request context in every log


nestjs-session

GitHub stars npm

Idiomatic session module for NestJS. Built on top of express-session


nestjs-cookie-session

GitHub stars npm

Idiomatic cookie session module for NestJS. Built on top of cookie-session


nestjs-roles

GitHub stars npm

Type safe roles guard and decorator made easy


nestjs-injectable

GitHub stars npm

@Injectable() on steroids that simplifies work with inversion of control in your hexagonal architecture


nest-ratelimiter

GitHub stars npm

Distributed consistent flexible NestJS rate limiter based on Redis


create-nestjs-middleware-module

GitHub stars npm

Create simple idiomatic NestJS module based on Express/Fastify middleware in just a few lines of code with routing out of the box


nestjs-configure-after

GitHub stars npm

Declarative configuration of NestJS middleware order

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].