nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
67.79k stars 7.64k forks source link

SocketIO + extraHeaders + CORS #1482

Closed JulienStitelet closed 5 years ago

JulienStitelet commented 5 years ago

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

using the default @WebSocketGateway() decorator will not help using socket.io + extraHeaders + cors

Expected behavior

I was looking for the optional property of socketIO : handlePreflightRequest for example the possible property into GatewayMetadata interface (see after the extends I had to write)

Minimal reproduction of the problem with instructions

Just try using nestjs, with default @WebSocketGateway(), and access from another url than the nestjs running one. (myself was on angular7 port 4200 where nestjs is in 3001) example frontend code:

var sockets = {};
function startSocketIO(token){
sockets[token] = io('http://localhost:3001', {
                transportOptions: {
                    polling: {
                        extraHeaders: {
                            'authorization': token
                        }
                    }
                }
            });
}

What is the motivation / use case for changing the behavior?

I wanted my frontend be able to connect to nestjs websocket host. I had to extend the current GatewayMetadata type to add handlePreflightRequest middleware like

import { GatewayMetadata } from '@nestjs/websockets';
export interface GatewayMetadataExtended extends GatewayMetadata {
  handlePreflightRequest: (req, res) => void;
}
const options = {
  handlePreflightRequest: (req, res) => {
    const headers = {
      'Access-Control-Allow-Headers': 'Content-Type, authorization, x-token',
      'Access-Control-Allow-Origin': req.headers.origin,
      'Access-Control-Allow-Credentials': true,
      'Access-Control-Max-Age': '1728000',
      'Content-Length': '0',
    };
    res.writeHead(200, headers);
    res.end();
  },
} as GatewayMetadataExtended;

@WebSocketGateway(options)

Environment


Nest version: 5.4.0
"@nestjs/websockets": "^5.6.2",



For Tooling issues:
- Node version: 8.11.3  
- Platform:  mac 

Others:

kamilmysliwiec commented 5 years ago

You can always extend the default socket.io adapter: https://docs.nestjs.com/websockets/adapter and pass handlePreflightRequest in there.

lock[bot] commented 5 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.