Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fastify Session don't save value to redis in NestJS #25

Open
DevDJpl opened this issue May 14, 2023 · 0 comments
Open

Fastify Session don't save value to redis in NestJS #25

DevDJpl opened this issue May 14, 2023 · 0 comments

Comments

@DevDJpl
Copy link

DevDJpl commented May 14, 2023

When I try to save a value in the Redis Session in NestJS with the Fastify adapter, it does not give me an error, but this value is not saved in the Redis database and is visible locally within the function and not in another. Although during the Fastify session registration, the session id value, which is also saved in the cookie, is visible in the database. And I can't figure it out why it doesn't save the values ​​I want to insert in Redis

My Code:

//Register Session (main.ts)
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { FastifyInstance } from 'fastify';
import fastifyCookie, { CookieSerializeOptions } from '@fastify/cookie';
import fastifyCsrf from '@fastify/csrf-protection';
import Redis from 'ioredis';
import RedisStore from '@mgcrea/fastify-session-redis-store';
import fastifySession from '@mgcrea/fastify-session';
import { randomBytes } from 'crypto';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  );
  const fastifyInstance: FastifyInstance = app.getHttpAdapter().getInstance();
  fastifyInstance
    .addHook('onRequest', async (req, res) => {
      req.socket['encrypted'] = process.env.NODE_ENV === 'production';
      res.header('X-Powered-By', 'CyberSecurity');
    })
    .decorateReply('setHeader', function (name: string, value: unknown) {
      this.header(name, value);
    })
    .decorateReply('end', function () {
      this.send('');
    });
  const configService = app.get(ConfigService);
  const port = configService.get<string>('PORT', '');
  
  // XCSRF - Protection
  await app.register(fastifyCsrf, {
    sessionPlugin: '@fastify/cookie',
    cookieKey: 'csrf-token',
    cookie: (cookieOptions: CookieSerializeOptions) => ({
      httpOnly: true,
      sameSite: 'strict',
      path: '/',
      secure: false,
      signed: false,
      ...cookieOptions,
    }),
    secret: randomBytes(32).toString('base64'),
  } as any);

  // Session
  const redisClient = new Redis({
    host: process.env.REDIS_HOST,
    port: Number(process.env.REDIS_PORT),
  });
  await app.register(fastifySession, {
    secret: randomBytes(32).toString('base64'),
    store: new RedisStore({
      client: redisClient,
      prefix: 'session:',
      ttl: Number(process.env.REFIS_TTL),
    }),
    cookieName: 'facebook-sid',
    cookie: {
      httpOnly: true,
      sameSite: 'strict',
      path: '/',
      secure: false,
      signed: false,
      maxAge: Number(process.env.REDIS_TTL),
    },
  });

  await app.listen(port);
}
bootstrap();




// Set value & read from Session (app.controller.ts)
@Get('/csrf-token')
  async get(@Req() req, @Res() res) {
    const csrfToken = await res.generateCsrf();
    req.session.csrfToken = csrfToken;
    //req.session.set(csrfToken);
    console.log(req.session.csrfToken); //return req.session.csrfToken => string token
    res.send({ 'csrf-token': csrfToken });
  }

  @Get('/csrf-token2')
  async get2(@Req() req) {
    console.log(req.session.csrfToken);
    return { 'Session Data:': req.session.csrfToken }; //return req.session.csrfToken => undefined
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant