2020-02-13
4083
#nestjs
Maciej Cieślar
13963
Feb 13, 2020 ⋅ 14 min read

Scalable WebSockets with NestJS and Redis

Maciej Cieślar A JavaScript developer and a blogger at mcieslar.com.

Recent posts:

TypeScript logo over a pink and white background.

Drizzle vs. Prisma: Which ORM is best for your project?

Compare Prisma and Drizzle ORMs to learn their differences, strengths, and weaknesses for data access and migrations.

Temitope Oyedele
Nov 21, 2024 ⋅ 10 min read
Practical Implementation Of The Rule Of Least Power For Developers

Practical implementation of the Rule of Least Power for developers

It’s easy for devs to default to JavaScript to fix every problem. Let’s use the RoLP to find simpler alternatives with HTML and CSS.

Timonwa Akintokun
Nov 21, 2024 ⋅ 8 min read
Rust logo over black marble background.

Handling memory leaks in Rust

Learn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.

Ukeje Goodness
Nov 20, 2024 ⋅ 4 min read
Robot pretending to be a person.

Using curl-impersonate in Node.js to avoid blocks

Bypass anti-bot measures in Node.js with curl-impersonate. Learn how it mimics browsers to overcome bot detection for web scraping.

Antonello Zanini
Nov 20, 2024 ⋅ 13 min read
View all posts

12 Replies to "Scalable WebSockets with NestJS and Redis"

  1. I’m not sure the interface AuthenticatedSocket was ever mentioned. Is this the correct typing?

    interface AuthenticatedSocket extends Socket {
    auth: {
    userId: string,
    }
    }

  2. Why implement your own solution over using socket.io-redis? i havn’t actually used socket.io-redis (currently trying to figure out the best solution) but it seems it abstracts the “socket state” so you don’t have to write your own implementation?

  3. socket.io-redis requires sticky session which is not available everywhere. Plus this way we got more control over how the connections are stored and used.

  4. Please I’m dealing with this now. How then can this be solved using s SPA like angular. I’m not aware that I can use sticky sessions with angular 8 but what are your thoughts? Can this solution work with jwt?

  5. Hello
    How I can use this websocketgateway in conjunction with graphql subscription?
    I can not find any tutorial that make relation between nestjs, graphql and socket.io

  6. I attempted to enable the swagger plugin but it is causing issues with the custom redis provider.

    https://docs.nestjs.com/openapi/introduction

    “`
    __metadata(“design:paramtypes”, [typeof (_a = typeof redis_providers_1.RedisClient !== “undefined” && redis_providers_1.RedisClient) === “function” ? _a : Object, typeof (_b = typeof redis_providers_1.RedisClient !== “undefined” && redis_providers_1.RedisClient) === “function” ? _b : Object])
    ^

    ReferenceError: redis_providers_1 is not defined
    at Object. (/usr/src/app/api/dist/main.js:2685:58)
    at __webpack_require__ (/usr/src/app/api/dist/main.js:749:30)
    at fn (/usr/src/app/api/dist/main.js:60:20)
    at Object. (/usr/src/app/api/dist/main.js:2566:25)
    at __webpack_require__ (/usr/src/app/api/dist/main.js:749:30)
    at fn (/usr/src/app/api/dist/main.js:60:20)
    at Object. (/usr/src/app/api/dist/main.js:2533:36)
    at __webpack_require__ (/usr/src/app/api/dist/main.js:749:30)
    at fn (/usr/src/app/api/dist/main.js:60:20)
    at Object. (/usr/src/app/api/dist/main.js:2503:35)
    “`

  7. Congratulations on the content, I am learning a lot. Just a note, if you use the emitToAuthenticated method elsewhere in the code, even those who are not authenticated have access to messages sent through the socket. How to fix this?

  8. Hello, great article. I implemented your code and it works fine when I import the SharedModule and use the RedisPropagatorService from one of my application service. However when I do the same from another application service I get the following error:

    [Nest] 29876 – 07/28/2021, 11:02:25 AM ERROR [ExceptionHandler] A circular dependency has been detected. Please, make sure that each side of a bidirectional relationships are decorated with “forwardRef()”.
    Error: A circular dependency has been detected. Please, make sure that each side of a bidirectional relationships are decorated with “forwardRef()”.

    This is happening when RedisModule gets instantiated and the RedisService has an undefined value during the NestJS insertProvider call during app creation.

    There are no conflicting references that should cause any circular references between these services and I am puzzled how come it works fine from one service and not from the other.

    Any help would be much appreciated.

  9. Thanks for the great tutorial.

    I had an issue while testing my application after adding Redis as described here. The problem was that the connections to Redis are never closed, so jest never exits, breaking my CI pipeline. Adding a onApplicationShutdown function where we disconnect the redis clients did the tricks.

    “`
    @Injectable()
    export class RedisService implements OnApplicationShutdown {
    private readonly logger = new Logger(RedisService.name)

    constructor(
    @Inject(REDIS_SUBSCRIBER_CLIENT)
    private readonly redisSubscriberClient: RedisClient,
    @Inject(REDIS_PUBLISHER_CLIENT)
    private readonly redisPublisherClient: RedisClient,
    ) {}

    onApplicationShutdown() {
    this.redisPublisherClient.disconnect()
    this.redisSubscriberClient.disconnect()
    }
    “`

    @Majiec would you consider adding this to the tutorial, saving someone some time in the future? I would also argue it is good practice closing the connections on shutdown anyway.

Leave a Reply