Running NATS as WebSocket Server

·

2 min read

NATS is a messaging platform that can connect multiple technologies together and comes to the browser as well.

Nats comes with WebSocket inbuilt, which can help in designing real-time systems easily. Yes, you don't need any external servers.

You can Start the Nats server with a single command, If you have installed in locally

nats-server

But if you can running in docker mode then you can use

docker run -d --name nats-main -p 4222:4222 -p 6222:6222 -p 8222:8222 nats

Nats server by default comes with WebSocket disabled, so we need to enable it, and as much as you can do it using a command, I prefer using a conf file.

websocket 
{
    port: 8080
    no_tls: true
}

This can be any file with a .conf extension. All we are saying is, "Run web sockets in Port 8080 with NoTLS.

Then change the command line or docker to use the config, below are the examples

Command Line

nats-server -c .\nats-server.conf

Output will show the Web socket is enabled

If you using docker then use the following command

docker run -d --name nats-main -p 4222:4222 -p 6222:6222 -p 8222:8222 nats -c .\nats-server.conf

In this blog post I covered a configuration which are for development, If you want to include security and cross cutting concerns then read about the full configuration here

Some troubleshooting areas:

  • If you've set your browser to block non-secure connections, WS won't work. You'll need a certificate to make it work, which you'll need to change to WSS.

Did you find this article valuable?

Support satish by becoming a sponsor. Any amount is appreciated!