Use websocket middleware return response 401

Hi, I’m making a websocket middleware , I want to response 401 from middleware.
Can someone help me?
Thanks.

This is my websocket middleware:

  async wsHandle({ request, response }, next) {


    let token =request.only('token').token;

    await axios.get('auth server url', {
      headers: {
        'Accept': 'application/json',
        'Authorization': token,
      },
    })
      .then(async (response) => {
        await next();
      })
      .catch(err => {
        if (err.response) {
          let err_code = err.response.status.toString()
          //This response can't return responses.
          response.status(err_code).send(err.response.data.message)
        }
      });
  }

You cannot make standard response with HTTP status codes in websocket connections.

Simply throw an exception from the middleware and AdonisJs will send that error to the channel on('error') event listener on the client.

3 Likes

Thank you.
I got it. :smiley: