Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 133 ยท Networking and HTTP

UDP, DNS and Other Protocols

Learn UDP datagrams with node:dgram, how DNS lookups really work in Node.js, IP address helpers, and when to use HTTP/2, TLS and HTTP/3, with runnable loopback examples.

TCP and HTTP get most of the attention, but a Node.js program often has to speak other protocols too. UDP sends small independent messages with no connection at all. DNS turns names such as shop.test into addresses before any connection can start. TLS encrypts a connection, and HTTP/2 makes web traffic more efficient. This lesson is a tour of those building blocks and the Node modules behind them: dgram, dns, net helpers, http2 and tls.

You will send real UDP datagrams between two sockets, write a tiny DNS server by hand and query it with Node's own resolver, and run an HTTP/2 conversation on loopback. Our sandbox has no external network, so everything talks to 127.0.0.1. Code that needs certificates or the real internet is shown read-only and clearly labelled.

UDP in one minute

TCP is like a phone call: you connect, talk, and the line guarantees that what you say arrives in order. UDP (User Datagram Protocol) is like postcards. Each datagram is one self-contained message. There is no connection, no guarantee that it arrives, no guarantee about order, and no retransmission. In exchange it is very cheap and has no waiting for handshakes.

TCP (net) UDP (dgram)
Connection Yes, set up first None
Delivery Reliable, retransmitted Best effort, may be lost
Order Guaranteed Not guaranteed
Boundaries None (a byte stream) Kept: one send is one message
Typical uses Web, databases, SSH DNS, game state, metrics, video calls, discovery

The last row of "boundaries" matters: in the TCP lesson you saw that writes can be merged or split. With UDP, one send() arrives as exactly one 'message' event (or is lost entirely).

Your first datagram exchange

dgram.createSocket('udp4') creates an IPv4 UDP socket. A server binds to an address and port and listens for 'message' events; a client simply calls send() with a destination. As in the TCP lesson, bind to 127.0.0.1 and port 0 to get a free port, then read it from socket.address().

Node.js A UDP echo server and client

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice how little ceremony there is. The client never "connected". The server learned who sent the datagram from the second argument of 'message', an object with address, family and port, and used it to answer. Each side must close() its socket, otherwise the process keeps running because an open socket keeps the event loop alive.

The client also got an automatic local port: the first send() on an unbound socket binds it to a random port behind the scenes.

A single UDP datagram can carry at most 65,507 bytes of payload over IPv4, and anything larger than the network's MTU (around 1,500 bytes on Ethernet) gets fragmented, which makes loss more likely. Keep datagrams small, ideally under about 1,200 bytes, if they have to cross real networks.

Message boundaries are kept

Send three separate messages and the receiver sees three separate events, never one merged blob. That is the opposite of TCP and it makes framing unnecessary. This example sends three datagrams and counts what arrives.

Node.js One send is one message

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two honest warnings. First, on loopback datagrams almost never get lost, but on a real network they can be dropped, duplicated or reordered, so the example sorts the list and we never claim an order. Second, the send callback only tells you the operating system accepted the datagram, not that anyone received it. If you need to know, your protocol must send an acknowledgement and resend after a timeout. That is how reliable protocols such as QUIC are built on top of UDP.

Connected UDP, broadcast and multicast

socket.connect(port, address) on a UDP socket does not open a connection. It only sets a default destination so you can call send(msg) without repeating it, and makes the socket ignore datagrams from anywhere else. Two more features you may meet:

  • Broadcast (socket.setBroadcast(true)): one datagram to every machine on the local network. Used for "who is here?" discovery.
  • Multicast (socket.addMembership('239.1.2.3')): one datagram to every machine that joined a group address.

Both need a real network interface, so we do not run them in the editor.

NODE
// Read-only: a LAN discovery beacon (needs a real network)
import dgram from 'node:dgram';

const beacon = dgram.createSocket({ type: 'udp4', reuseAddr: true });
beacon.bind(41234, () => {
  beacon.setBroadcast(true);
  setInterval(() => {
    beacon.send('printer-01 is here', 41234, '255.255.255.255');
  }, 2000);
});

Names to addresses: how DNS lookups work

Computers connect to numbers; people use names. The Domain Name System is the phone book that connects the two. Node gives you two very different ways to use it, and mixing them up causes real confusion.

  1. dns.lookup(name) calls the operating system's resolver (the C function getaddrinfo). It honours /etc/hosts, the OS cache and OS settings. This is what fetch, http and net.connect use. It runs on the libuv thread pool, because the OS function is blocking.
  2. dns.resolve*() (resolve4, resolveMx, resolveTxt, ...) skips the OS and sends DNS queries over the network itself, using UDP (and TCP as fallback). It does not read /etc/hosts. Nothing is blocked on the thread pool.

A frequent bug: dns.lookup('localhost') works while dns.resolve4('localhost') fails, because only the first one reads the hosts file.

Node.js dns.lookup uses the operating system

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The error code is ENOTFOUND when the resolver answers that the name does not exist. Our sandbox has no DNS server to ask, so it reports EAI_AGAIN (a temporary failure, try again later), which is why the example prints a check instead of the code itself. Other codes you will see in production: ETIMEOUT and ECONNREFUSED (the DNS server did not answer).

Without family: 4 or all: true, lookup returns one address, and on a machine with IPv6 localhost may be ::1 rather than 127.0.0.1. That is why servers listening only on 127.0.0.1 sometimes refuse a client that connects to localhost. When you write examples or tests, use the literal 127.0.0.1.

dns.lookup is not "free". Every call uses a thread-pool slot (4 by default), so a burst of lookups can delay file reads and crypto work running on the same pool. Reuse connections with keep-alive, and cache results when you call many hosts.

A DNS server in 40 lines (and a client that uses it)

We cannot reach real DNS servers, but DNS is just UDP with a binary message format, so we can run our own and point Node's resolver at it. The resolver class dns.Resolver lets you choose the servers with setServers().

A DNS message starts with a 12-byte header (id, flags, counts), followed by the question: the name as length-prefixed labels (4shop4test0), a 2-byte type (1 means an A record, an IPv4 address) and a 2-byte class. An answer repeats the question, then adds the record: a pointer back to the name, type, class, a TTL (how long the answer may be cached, in seconds) and the 4 address bytes.

Node.js Our own DNS server over UDP

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output: the resolver sent a real DNS query over UDP, our handler parsed it, and the resolver parsed our hand-built answer. With { ttl: true } you get the TTL too. For a name the server does not know, we answered with the code NXDOMAIN and Node turned that into ENOTFOUND.

This is also why DNS uses UDP: a question and an answer each fit in one small datagram, so no connection setup is needed. Large answers fall back to TCP.

Other record types and real-world use

With real servers you can ask for more than addresses:

NODE
// Read-only: needs real internet access
import dns from 'node:dns/promises';

console.log(await dns.resolve4('nodejs.org'));        // A records (IPv4)
console.log(await dns.resolve6('nodejs.org'));        // AAAA records (IPv6)
console.log(await dns.resolveMx('example.com'));      // mail servers: [{ exchange, priority }]
console.log(await dns.resolveTxt('example.com'));    // TXT records (SPF, verification tokens)
console.log(await dns.reverse('8.8.8.8'));            // reverse lookup: address to names
console.log(dns.getServers());                        // the servers Node will ask

dns.setDefaultResultOrder('ipv4first') changes the order in which lookup returns addresses. Node 20+ defaults to verbatim (whatever the OS gives), and since Node 20 net.connect also tries several addresses (the "happy eyeballs" strategy) so a broken IPv6 route does not make a request hang.

The resolve family, run against a zone of our own

The read-only snippet above needs the internet. Here is the same family of calls against our own server, this time with a small zone: a table of names and record types. It answers MX (mail servers), TXT (free text: SPF policies, ownership proofs), NS (name servers), SOA (zone metadata), CNAME (an alias), SRV (a service location with port) and PTR (the reverse direction, address to name). Each record type has its own binary layout, which the encodeRecord function writes; you do not need to memorize it, only to see that every resolve* method is one question type.

Node.js resolveMx, resolveTxt, resolveNs, resolveSoa, resolveSrv and reverse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Compare each line with what it is used for in practice:

Method Record Typical use
resolveMx MX Where does mail for this domain go? Lower priority numbers are tried first
resolveTxt TXT SPF, DKIM and DMARC policies, domain ownership tokens. Each record is an array of strings because long values are split in 255-byte chunks
resolveNs NS Which servers are authoritative for the zone
resolveSoa SOA The zone's serial (bumped on every change) and its refresh timing
resolveCname CNAME An alias pointing at another name
resolveSrv SRV Finds a service and port, for example _sip._tcp; sort by priority, then pick by weight
reverse PTR Name for an IP address; Node asks for 7.0.0.10.in-addr.arpa
resolveAny all Asks for every type at once; many servers refuse or truncate it, so do not rely on it

The failure at the end shows how errors map: our server answered NXDOMAIN for a name that has no MX record, so Node reports ENOTFOUND. A real server answers a known name with no records of that type with an empty successful response, and Node reports it as ENODATA. Handle both codes when you check for optional records. dns.setServers() changes the servers for the whole process, whereas a dns.Resolver instance, as used here, keeps the setting local (the better choice in libraries and tests). For mail, resolveMx plus resolveTxt is how you check that a domain can receive mail and has an SPF policy, as described in Sending Email with Nodemailer.

More lookups, NAPTR and socket options

Three smaller pieces round out the DNS and UDP API. The code below needs the internet or OS service tables, so it is shown read-only.

JavaScript
import dns from 'node:dns/promises';
import dgram from 'node:dgram';

// lookupService: the reverse of lookup(), address + port -> host name + service name
console.log(await dns.lookupService('127.0.0.1', 22)); // { hostname: 'localhost', service: 'ssh' }

// resolveNaptr: NAPTR records (used by telephony and some service discovery),
// each with flags, service, regexp, replacement, order and preference
console.log(await dns.resolveNaptr('example.com'));

// resolve(name, rrtype) is the general form; rrtype can be 'A', 'AAAA', 'MX', 'NAPTR', ...
console.log(await dns.resolve('example.com', 'TXT'));

// dgram.createSocket options: IPv6-only sockets and kernel buffer sizes
const socket = dgram.createSocket({
  type: 'udp6',
  ipv6Only: true,
  recvBufferSize: 1024 * 1024,
  sendBufferSize: 1024 * 1024,
});

lookupService asks the operating system, so the service name (ssh, http) comes from its services table. The receive and send buffer sizes matter for busy UDP servers: when datagrams arrive faster than your code reads them and the kernel buffer is full, the extra packets are silently dropped, and a bigger recvBufferSize gives you more slack. Remember that dns.resolve() and its relatives are also available as methods on a dns.Resolver, so you can point any of them at your own servers.

IP address helpers in net

The net module has small, pure helpers that need no network at all, handy for validating input such as a configuration value or a forwarded-for header.

Node.js net.isIP, net.isIPv4 and net.BlockList

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A BlockList is the right tool when you must stop users from making your server fetch internal addresses (an attack called SSRF, covered in Web Application Security). Remember to check the address after DNS resolution, not the hostname, since an attacker controls what their domain name points to.

HTTP/2: many requests on one connection

HTTP/1.1 handles one request at a time per connection, so browsers open several connections per site. HTTP/2 keeps a single connection and multiplexes many independent request/response streams over it, compresses headers, and lets servers push data efficiently. The node:http2 module implements it. Browsers only speak HTTP/2 over TLS, but the protocol also exists in cleartext ("h2c"), which is perfect for a loopback demo.

Node.js HTTP/2 on loopback with three parallel requests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

HTTP/2 headers include pseudo-headers that start with a colon (:method, :path, :status). The 'stream' event gives you a duplex stream per request, and Promise.all keeps the printed order fixed even though the three requests were in flight together.

In real applications you rarely write this by hand. A framework or reverse proxy (nginx, a CDN) terminates HTTP/2 for browsers and your Node app speaks plain HTTP/1.1 behind it. Use http2 directly for gRPC-style services and special clients. Also, fetch in Node does not currently speak HTTP/2 by default.

HTTP/2 in more detail: settings, push, ping and stream limits

The first example hid several concepts. A request is one stream, and the 'stream' event gives you a duplex stream per request. A session is the single connection that carries them. When a session starts, both sides send a SETTINGS frame announcing limits such as maxConcurrentStreams (how many requests may be open at once), initialWindowSize (the flow-control window per stream, in bytes) and enablePush. Node exposes them as session.localSettings and session.remoteSettings, and the settings option of createServer changes yours. HTTP/2 also has its own flow control, so a slow reader cannot make a fast writer buffer endlessly (the same back-pressure idea as in pipeline and Backpressure), and HPACK header compression, which makes repeated headers such as cookies cost only a few bytes.

The example below shows four things on loopback: the announced settings, a server push (the server sends /style.css before the client asks for it), a ping for round-trip measurement, and what happens when a client sends more requests than the server allows at once: the extra streams wait for a free slot.

Node.js HTTP/2 settings, server push, ping and concurrent stream limits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Some practical notes. Server push is part of the protocol and Node supports it (stream.pushStream, after checking stream.pushAllowed), but browsers have removed it because it was hard to use well; 103 Early Hints and <link rel="preload"> replaced it, so treat push as a feature for non-browser clients. The compatibility API (http2.createServer((req, res) => ...)) gives you the familiar req and res objects, so an Express-style handler can run over HTTP/2 without a rewrite, although the 'stream' API is more direct. To end a session politely use session.close(), which lets open streams finish and sends a GOAWAY frame, and session.destroy() to cut it off. Browsers speak HTTP/2 only over TLS; the TLS section below shows how that is set up, including how one port can serve both HTTP/2 and HTTP/1.1.

TLS: encryption for any connection

TLS (Transport Layer Security) wraps a TCP connection in encryption and proves the server's identity with a certificate. HTTPS is HTTP over TLS. In Node, tls.createServer() and tls.connect() mirror net, and https.createServer() mirrors http. They need a private key and a certificate, which we cannot generate inside the editor, so this is read-only:

NODE
// Read-only: needs key.pem and cert.pem files on your machine
import https from 'node:https';
import fs from 'node:fs';

const server = https.createServer({
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem'),
}, (req, res) => {
  res.end('secure hello\n');
});
server.listen(8443);
Terminal
# create a self-signed certificate for local experiments only
openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem -days 30 -subj "/CN=localhost"

Never disable certificate checks (rejectUnauthorized: false, or the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0) outside local experiments: it removes exactly the protection TLS exists to provide. In production, terminate TLS at a reverse proxy or use certificates from a trusted authority such as Let's Encrypt. See Deploying Node.js Applications for the usual setups.

Running TLS on loopback: trust, ALPN and mutual TLS

Everything below runs, because the examples embed a throwaway test certificate in the code. We made a self-signed EC certificate for localhost and 127.0.0.1 with OpenSSL; it is valid until 2125 and its private key is printed right here, so it proves nothing about identity to anyone. Never reuse such a key outside a demo.

The first demo is a secure server created with http2.createSecureServer({ key, cert, allowHTTP1: true }). During the TLS handshake the client and server agree on a protocol with ALPN (Application-Layer Protocol Negotiation): the client offers h2 and http/1.1, and the server picks one. So one port serves HTTP/2 to modern clients and HTTP/1.1 to older ones, which is how real sites work. Three clients try it: an HTTPS client that trusts the certificate (it passes ca), one that does not, and an HTTP/2 client.

Node.js An HTTPS and HTTP/2 server with a test certificate, and who trusts it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the three results. The trusted client verified the chain and the host name (the certificate lists localhost and 127.0.0.1 in its subject alternative names; modern clients ignore the common name), then spoke TLS 1.3 over HTTP/1.1. The untrusted client was refused with DEPTH_ZERO_SELF_SIGNED_CERT, which is exactly what protects users from a stranger's certificate; the cure is to trust the specific certificate (ca), never to switch the check off. The HTTP/2 client negotiated h2 over the same port. A public site uses a certificate from a trusted authority (such as Let's Encrypt, sending the full chain), and renews it before it expires.

Mutual TLS (mTLS) turns the identity check around as well: the server demands a certificate from the client and trusts only certificates you list. It is common between internal services, where a service identity is more reliable than a shared secret in a header. tls.createServer with requestCert: true and rejectUnauthorized: true enforces it, and socket.getPeerCertificate() tells you who connected.

Node.js Mutual TLS: the server only accepts a known client certificate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first client presents the certificate the server trusts and is greeted by the name inside it. The second connects without one: the handshake fails and the server logs tlsClientError. Notice that with TLS 1.3 the client sees the failure slightly after its own handshake has finished, as an alert such as ERR_SSL_TLSV13_ALERT_CERTIFICATE_REQUIRED. Plain https.createServer accepts the same options (requestCert, ca), and req.socket.authorized and req.socket.getPeerCertificate() give you the identity inside a normal HTTP handler. Other options you will meet: minVersion (for example 'TLSv1.2'), ciphers, passphrase for encrypted keys, SNICallback to choose a certificate per host name, and session tickets for faster reconnects. Keep keys out of the repository (see Secrets and Configuration).

HTTP/3 and QUIC: where things stand

HTTP/3 runs over QUIC, a protocol built on UDP that bundles encryption, multiplexing and loss recovery, and avoids the "head of line blocking" of TCP (where one lost packet stalls every stream). Browsers and CDNs already use it widely. Node.js does not ship a stable HTTP/3 or QUIC API in its LTS line; a node:quic implementation has been under development as an experimental feature. In practice the browser speaks HTTP/3 to your CDN or proxy, which talks HTTP/1.1 or HTTP/2 to Node. Check the release notes of your Node version before relying on any QUIC API.

Choosing a protocol

  • HTTP/1.1 or HTTP/2 for APIs and websites. Start with the http module.
  • WebSocket for two-way messages with browsers: WebSockets.
  • TCP (net) for custom reliable protocols: TCP Servers and Clients.
  • UDP for small, frequent, loss-tolerant messages (metrics, discovery, game positions) and for protocols such as DNS that define their own retry rules.
  • TLS whenever data crosses an untrusted network.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main difference between UDP and TCP?

    UDP sends independent datagrams with no connection, no retransmission and no ordering guarantee, but each send arrives as one whole message (or not at all).
  2. 2. What does the callback of socket.send() on a UDP socket tell you?

    UDP has no acknowledgements. The callback only reports whether the local send succeeded, so a protocol that needs confirmation must add its own replies.
  3. 3. Which statement about dns.lookup() and dns.resolve4() is correct?

    lookup() calls getaddrinfo on the thread pool and respects the hosts file; resolve*() queries DNS servers directly over the network. net and http use lookup().
  4. 4. Why do you check an address with net.BlockList after DNS resolution when defending against SSRF?

    A harmless-looking hostname can resolve to 10.x.x.x or 127.0.0.1. Validating the resolved IP is what blocks the request.
  5. 5. How does HTTP/2 differ from HTTP/1.1 on the wire?

    HTTP/2 interleaves many independent streams on a single connection and compresses headers, which reduces connection overhead.

Summary

  • UDP (dgram) sends independent datagrams with no connection and no delivery guarantee; one send() is one 'message'. Always close() the sockets, bind to 127.0.0.1 and port 0 in demos.
  • dns.lookup() uses the operating system and the thread pool; dns.resolve*() and dns.Resolver query DNS servers directly over UDP. Expect ENOTFOUND, EAI_AGAIN and ETIMEOUT.
  • The resolve* family maps to record types: MX, TXT, NS, SOA, CNAME, SRV and PTR (reverse); a missing record shows as ENOTFOUND or ENODATA, and a dns.Resolver keeps its server list local.
  • net.isIP() and net.BlockList validate and classify addresses without any network.
  • http2 multiplexes streams over one connection, announces limits in SETTINGS frames, and negotiates h2 or http/1.1 through ALPN on a secure server; mutual TLS authenticates clients with requestCert.
  • tls and https need certificates, and certificate checks must never be switched off in production.
  • HTTP/3 and QUIC are handled by CDNs and proxies today; Node itself has no stable API for them.

Next: Child Processes