Setup: WebSocket, With Token Authentication
WebSocket, but clients must authenticate using a single shared token instead of a username/password pair.
1. NATS server setup
# Enable token authentication instead of username/password.
#
# Token auth is a single shared secret every client must present to connect
# — it is mutually exclusive with username/password at the NATS protocol
# level (see the "token" option in @nats-io/nats-core: "mutually exclusive
# of user and pass"). Unlike Tutorial 2 (No TLS, With Credentials), this
# configuration does NOT use `accounts`, so there is no SYS -> APP export
# and System Service ($SYS.>) monitoring is not available here.
listen: 0.0.0.0:4222
http_port: 8222
# WebSocket transport — required for the browser to connect at all.
websocket {
port: 8080
no_tls: true
}
# JetStream — required for KV buckets and Streams.
jetstream {
store_dir: "/data"
}
# A single shared token every client must present to connect.
authorization {
token: "s3cr3t-shared-token"
}
Run NATS server Docker
docker run -d --name nats-server \
-p 4222:4222 -p 8222:8222 -p 8080:8080 \
-v $(pwd)/nats-server.conf:/etc/nats/nats-server.conf:ro \
nats:latest \
-c /etc/nats/nats-server.conf
One-time nats-cli connection setup
nats context add tutorial-token \
--server="nats://10.135.32.227:4222" \
--token="s3cr3t-shared-token" \
--selectIn the Connection panel, set Auth mode to Token — the Username/Password fields are hidden while Token is selected, since NATS treats the two as mutually exclusive: a client authenticates with either a username/password pair or a token, never both.
In Connection section, enter:
- NATS server host
- 10.135.32.227
- WS port
- 8080
- TLS (wss)
- off
- Auth mode
- Token
- Token
- s3cr3t-shared-token
2. Subscription to subject / KV bucket / stream
In the Subscriptions form: Type: Subject · Target: orders.>
No setup required — just add the subscription above.
In the Subscriptions form: Type: KV Bucket · Target: my-bucket
nats kv add my-bucketIn the Subscriptions form: Type: JetStream Stream · Target: ORDERS · Filter: orders.created (optional)
nats stream add ORDERS --subjects "orders.>" --storage file \
--retention limits --max-msgs=-1 --max-bytes=-1 --max-age=0 --defaultsThis configuration authenticates with a single shared token and has no `accounts`/`system_account`, so $SYS.> system events are never published (the default global account does not publish advisories). See Tutorial 2 (No TLS, With Credentials) to enable system monitoring instead.
3. Messages creation
nats pub orders.created '{"id": 1, "total": 42.5}'nats kv put my-bucket hello worldnats pub orders.created '{"id": 1}'