Tiếp tục với series, ở Bài 30 TasksService đã biết phát event. Bài này mình sẽ giới thiệu với mọi người về WebSocket trong NestJS để báo realtime cho client khi task đổi trạng thái.
1. WebSocket, socket.io và gateway.
WebSocket là kết nối hai chiều luôn mở, server chủ động gửi dữ liệu cho client. Trong NestJS, nơi nhận và gửi message là gateway: provider gắn @WebSocketGateway(), chạy trên socket.io hoặc ws.
Subscription ở Bài 25 cũng dùng WebSocket nhưng khác:
graphql-wslà giao thức của GraphQL: client gửi câusubscriptiontới/graphql.- socket.io có giao thức riêng: event tự đặt tên, room, ack, tự kết nối lại, dự phòng bằng long-polling. Client dùng
socket.io-client, path mặc định/socket.io/. - Hai bên chung cổng 3000 vì
@nestjs/graphqlchỉ nhận đúng path/graphql: đừng đặtpath: '/graphql'cho gateway.
npm install @nestjs/websockets @nestjs/platform-socket.io
nest g gateway tasks/task-events --flat --no-spec --format
Hai package bản 12.5.0 (socket.io 4.8.4); lệnh thứ hai thêm TaskEventsGateway vào TasksModule.
2. Xác thực khi kết nối.
Guard, pipe, interceptor toàn cục chạy cả cho gateway (filter toàn cục thì không). Mình tách phần kiểm tra token của JwtAuthGuard (Bài 20) ra để dùng chung:
- src/auth/auth.service.ts (đoạn trích: token sai, hết hạn hay user đã bị xoá đều trả null; guard chỉ còn gọi this.auth.verifyToken(request.headers.authorization), AuthModule thêm exports: [AuthService])
async verifyToken(authorization?: string): Promise<AuthUser | null> {
const [type, token] = authorization?.split(' ') ?? [];
if (type !== 'Bearer' || !token) {
return null;
}
const payload = await this.jwtService
.verifyAsync<{ sub: string }>(token)
.catch(() => null);
return payload
? this.prisma.user.findUnique({
where: { id: Number(payload.sub) },
select: AUTH_USER_SELECT,
})
: null;
}
Client gửi token trong auth lúc bắt tay (handshake). Middleware server.use() chạy trước khi socket kết nối nên từ chối được ngay, còn handleConnection() không chặn được message đến sớm. Socket hợp lệ được gắn một "request" cho guard và @CurrentUser():
- src/common/utils/get-req-res.ts (đoạn trích đầu hàm; Socket import type từ socket.io)
if (context.getType() === 'ws') {
// WebSocket: "request" dựng lúc handshake (TaskEventsGateway).
// Không có response: res rỗng để throttler bỏ qua phần ghi header
const client = context.switchToWs().getClient<Socket>();
return { req: client.data.req as AuthRequest, res: {} as Response };
}
- src/tasks/task-events.gateway.ts (đoạn trích, bỏ phần import)
// Cùng cổng với HTTP, path mặc định /socket.io/
@WebSocketGateway()
@UseFilters(new WsExceptionFilter())
export class TaskEventsGateway implements OnGatewayInit {
@WebSocketServer()
private readonly server: Server;
constructor(
private readonly auth: AuthService,
private readonly prisma: PrismaService,
) {}
// Middleware chạy lúc handshake: token sai thì không kết nối được
afterInit(server: Server): void {
server.use((socket, next) => {
const { token } = socket.handshake.auth as { token?: string };
const authorization = `Bearer ${token}`;
this.auth.verifyToken(authorization).then((user) => {
if (!user) {
return next(new Error('Unauthorized'));
}
// "request" cho guard toàn cục, throttler và @CurrentUser()
const { address: ip } = socket.handshake;
const req = { headers: { authorization }, ip, user };
socket.data.req = req as AuthRequest;
next();
}, next);
});
}
@Throttle({ default: { limit: 5, ttl: seconds(10) } })
@SubscribeMessage('project:join')
async joinProject(
@MessageBody() dto: JoinProjectDto,
@ConnectedSocket() client: Socket,
@CurrentUser() user: AuthUser,
): Promise<{ room: string }> {
const owned = await this.prisma.project.count({
where: { id: dto.projectId, ownerId: user.id },
});
if (owned === 0) {
throw new ProjectNotFoundException(dto.projectId);
}
const room = `project:${dto.projectId}`;
await client.join(room);
return { room }; // trả cho client qua ack
}
// Chỉ gửi cho room của project, không phát cho mọi người
@OnEvent(TASK_STATUS_CHANGED)
notify(event: TaskStatusChangedEvent): void {
this.server.to(`project:${event.projectId}`).emit('task:status', event);
}
}
TasksModule import thêm AuthModule. JwtAuthGuard chạy lại cho từng message: token hết hạn thì bị 401.
3. Room và phát sự kiện realtime.
Room là nhóm socket ở server: client.join(room) thêm socket vào, server.to(room).emit() gửi cho cả nhóm. Client gửi project:join kèm projectId; chỉ chủ project 1 vào được room project:1 nên sự kiện không đến tay người khác. Giá trị trả về đến client qua ack, được bọc { data } như REST.
Gateway nghe event bằng @OnEvent() (Bài 30) nên TasksService không biết gì về WebSocket: khi status thật sự đổi, update() phát new TaskStatusChangedEvent(id, task.projectId, task.title, task.status), class mới viết như TaskCompletedEvent.
4. Validation, giới hạn và CORS.
ValidationPipe toàn cục kiểm tra JoinProjectDto (projectId với @IsInt() @IsPositive()). Nhưng gateway chỉ gửi nguyên message của WsException, còn HttpException của pipe, guard thành "Internal server error":
- src/common/filters/ws-exception.filter.ts
import { type ArgumentsHost, Catch, HttpException } from '@nestjs/common';
import { BaseWsExceptionFilter, WsException } from '@nestjs/websockets';
// Lỗi HTTP (400, 401, 404, 429) -> WsException giữ status và message
@Catch()
export class WsExceptionFilter extends BaseWsExceptionFilter {
catch(exception: unknown, host: ArgumentsHost): void {
if (exception instanceof HttpException) {
const body = exception.getResponse();
exception = new WsException({
status: 'error',
statusCode: exception.getStatus(),
message:
typeof body === 'string'
? body
: (body as { message: unknown }).message,
});
}
super.catch(exception, host);
}
}
@Throttle() cho mỗi IP 5 lần project:join trong 10 giây (req.ip lấy từ handshake; sau reverse proxy mọi socket chung một IP, bài deploy (Bài 36) sẽ đổi sang đếm theo user). Chỉ message này bị giới hạn: throttler không chạy trong server.use(), nên số kết nối và số lần handshake (mỗi lần verify token, đọc user) phải chặn ở reverse proxy (giới hạn theo IP) hoặc tự đếm số socket của mỗi user. Origin và kích thước message đặt cho socket.io server qua adapter:
- src/common/socket-io.adapter.ts
import type { INestApplicationContext } from '@nestjs/common';
import { IoAdapter } from '@nestjs/platform-socket.io';
import type { Server, ServerOptions } from 'socket.io';
export class SocketIoAdapter extends IoAdapter {
constructor(
app: INestApplicationContext,
private readonly origins: string[],
) {
super(app);
}
createIOServer(port: number | undefined, options?: ServerOptions): Server {
return super.createIOServer(port, {
...options,
// HTTP long-polling: trình duyệt cần header CORS
cors: { origin: this.origins },
// WebSocket không bị CORS chặn: tự kiểm tra Origin (trình duyệt luôn gửi)
allowRequest: (req, callback) => {
const origin = req.headers.origin;
callback(null, !origin || this.origins.includes(origin));
},
maxHttpBufferSize: 16 * 1024, // message lớn hơn 16 KB: ngắt kết nối
} as ServerOptions);
}
}
main.ts thêm app.useWebSocketAdapter(new SocketIoAdapter(app, config.corsOrigins)), corsOrigins tách theo dấu phẩy từ biến môi trường mới CORS_ORIGINS (mặc định http://localhost:5173).
5. Thử với hai user.
Cài client (npm install -D socket.io-client), tạo file ở thư mục gốc project:
- ws.mjs
import { io } from 'socket.io-client';
const socket = io('http://localhost:3000', {
auth: { token: process.env.TOKEN }, // gửi một lần lúc handshake
transports: ['websocket'], // bỏ qua long-polling
});
const log = (name) => (data) => console.log(name, JSON.stringify(data));
socket.on('connect', () => {
const projectId = Number(process.env.PROJECT);
socket.emit('project:join', { projectId }, log('join')); // callback = ack
});
socket.on('task:status', log('task:status'));
socket.on('exception', log('exception'));
socket.on('connect_error', (error) =>
console.log('connect_error', error.message),
);
Reset dữ liệu như Bài 30, đăng ký An, tai tạo task 1 trong project 1. Hai terminal chạy TOKEN=<token> PROJECT=1 node ws.mjs với token của tai và của An, rồi tai đổi trạng thái task 1:
curl -X PATCH http://localhost:3000/api/v1/tasks/1 -H "$A" \
-H "Content-Type: application/json" -d '{"status":"doing"}'
# Terminal của tai:
# join {"data":{"room":"project:1"}}
# task:status {"taskId":1,"projectId":1,"title":"Viết bài WebSocket","status":"doing"}
# Terminal của An:
# exception {"status":"error","statusCode":404,"message":"Không tìm thấy project 1"}
# Không có token / token sai: connect_error Unauthorized
# PROJECT=abc: exception {...,"statusCode":400,"message":["projectId must be a positive number",...]}
# Lần join thứ 6 trong 10 giây: exception {...,"statusCode":429,...}
Origin lạ bị từ chối lúc handshake, message hơn 16 KB làm kết nối bị đóng, subscription /graphql vẫn chạy bình thường. Thử xong các bạn xoá ws.mjs.
Lưu ý: Token hết hạn thì socket vẫn nhận sự kiện của room đã vào (muốn chặt hơn thì ngắt socket lúc đó). Chạy nhiều instance cần @socket.io/redis-adapter (Redis từ Bài 27) kèm sticky session hoặc chỉ dùng transport websocket.
6. Lời kết.
Như vậy mình đã giới thiệu xong về WebSocket trong NestJS: gateway với socket.io, xác thực lúc handshake, room theo project, validation và CORS cho gateway. Bài sau mình sẽ giới thiệu về Microservices trong NestJS, tách phần thông báo thành service riêng.
Đăng ký nhận tin.
Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!





0 Comments