nats pub and nats sub: Test NATS Messaging
nats pub <subject> <message> publishes to a NATS subject and nats sub <subject> subscribes, both pointed at a server with -s.
The nats CLI is the standard tool for exercising a NATS server from the shell. In CI it verifies that your subjects route and that the server is reachable before app tests run.
What it does
nats pub sends a message to a subject; nats sub listens on a subject (wildcards allowed) and prints matching messages. Both connect to the server given by -s or the NATS_URL env var. nats request performs a request/reply round trip and surfaces the "no responders" condition.
Common usage
# publish
nats pub orders.created '{"id":1}' -s nats://localhost:4222
# subscribe and exit after one message
nats sub orders.* --count 1 -s nats://localhost:4222
# request/reply (fails fast if nobody is listening)
nats request orders.query 'ping' -s nats://localhost:4222Options
| Flag | What it does |
|---|---|
| -s <url> | Server URL, e.g. nats://localhost:4222 |
| --count <n> | Receive n messages then exit (sub) |
| --count <n> | Publish n messages (pub) |
| --creds <file> | NATS credentials file for auth |
| --queue <name> | Join a queue group (sub) |
In CI
Use nats sub --count 1 so the subscriber exits after receiving the expected message instead of blocking the job. Core NATS is fire-and-forget: a subscriber must already be running when you publish, or the message is dropped, so start sub before pub in a test.
Common errors in CI
"nats: error: no responders available for request" from nats request means no service is subscribed to that subject; start the responder first. "nats: error: nats: no servers available for connection" or "Connection refused" means the server is not up on 4222. "nats: error: nats: authorization violation" means missing or wrong --creds.