How to Run an HTTPS Server with Bun.serve
With Bun.serve, you can turn a server into an HTTPS server just by passing a private key and certificate to tls. You can then respond at URLs like https://localhost:8443/.
For local development with HTTPS (SSL/TLS) on localhost, the tricky parts are creating a certificate that no public CA has signed, such as a self-signed one, and getting clients to trust it. I used a test CA (certificate authority) made with OpenSSL, plus a certificate signed by that CA. I tested everything in a test environment: connecting with curl and Bun's fetch, the errors you get when something is wrong, passphrase-protected keys, per-hostname certificate selection (SNI), and forwarding from http:// to https://.
The test environment was Ubuntu 24.04 (x86_64), Bun 1.4.4, TypeScript 5.9.3 (@types/bun 1.4.4), OpenSSL 3.0.13, and curl 8.5.0. All servers ran on localhost. I did not test certificates from public CAs such as Let's Encrypt, connections from a browser, client certificates (mTLS), HTTP/3, Windows, or macOS. I checked the official documentation in the original files at the tag used for testing (bun-v1.4.4) on GitHub, and the links point there.
- 1. Create a test CA and a localhost certificate
- 2. Start the server with key and cert passed to tls
- 3. Without the CA, curl and fetch both refuse the connection
- 4. Passing a file path as a string causes an error at startup
- 5. Open a passphrase-protected key with passphrase
- 6. Select a certificate per hostname on one port
- 7. Forward requests that arrive over http:// to https://
- 8. Add http2: true to accept HTTP/2
- 9. Compare the time per new connection with HTTP
Create a test CA and a localhost certificate
curl and Bun's fetch will refuse a connection unless the certificate is signed by a CA they trust (I show this below). So I created one test CA and used it to sign a server certificate for localhost. The diagram below shows how the pieces fit together.

I created the certificates with the shell script below. I put localhost and 127.0.0.1 in the SAN (Subject Alternative Name) field of the server certificate. As the curl output later shows, curl matches this field against the hostname you access (here, localhost).
cd certs
# 1. Test CA
openssl req -x509 -newkey rsa:2048 -nodes -days 30 -subj "/CN=Test Local CA" -keyout ca-key.pem -out ca.pem 2>/dev/null
# 2. Key and certificate for localhost (put localhost and 127.0.0.1 in the SAN)
openssl req -newkey rsa:2048 -nodes -subj "/CN=localhost" -keyout key.pem -out server.csr 2>/dev/null
printf 'subjectAltName=DNS:localhost,IP:127.0.0.1\n' > san.ext
openssl x509 -req -in server.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -days 30 -extfile san.ext -out cert.pem 2>/dev/null
When I checked the certificate, the issuer was the test CA.
$ openssl x509 -in certs/cert.pem -noout -subject -issuer -ext subjectAltName
subject=CN = localhost
issuer=CN = Test Local CA
X509v3 Subject Alternative Name:
DNS:localhost, IP Address:127.0.0.1
ca-key.pem and key.pem are private keys. Do not commit them to a Git repository or share them with anyone. The CA created here is for testing only, so you can delete it when you are done.
Start the server with key and cert passed to tls
The server code only needs key and cert added to tls. As the official TLS documentation explains, you pass the file contents here. You can pass a file opened with Bun.file() as is.
// HTTPS server. Pass the contents of the files to key and cert
const server = Bun.serve({
port: 8443,
tls: {
key: Bun.file("./certs/key.pem"),
cert: Bun.file("./certs/cert.pem"),
},
fetch(req) {
const url = new URL(req.url);
return new Response(`こんにちは。${url.protocol} でつながっています\n`);
},
});
console.log(`起動しました: ${server.url}`);
When I ran it with bun server.ts, server.url started with https://. The port was set with port: 8443.
起動しました: https://localhost:8443/
When I accessed it with curl and passed the test CA with --cacert, I got a response. On the server side, req.url also started with https:.
$ curl -sS --cacert certs/ca.pem https://localhost:8443/
こんにちは。https: でつながっています
I ran -v and pulled out just the TLS part. The connection used TLS 1.3, and the localhost in the certificate matched the hostname I accessed.
$ curl -sv --cacert certs/ca.pem https://localhost:8443/ 2>&1 | grep -E 'ALPN|SSL connection|subject|issuer|using HTTP|^< HTTP'
* ALPN: curl offers h2,http/1.1
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384 / X25519 / RSASSA-PSS
* ALPN: server did not agree on a protocol. Uses default.
* subject: CN=localhost
* subjectAltName: host "localhost" matched cert's "localhost"
* issuer: CN=Test Local CA
* using HTTP/1.x
< HTTP/1.1 200 OK
Without the CA, curl and fetch both refuse the connection
When I accessed the server without --cacert, curl stopped with exit code 60. The test CA is not in the list of CAs that curl trusts by default.
$ curl -sS https://localhost:8443/
curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: https://curl.se/docs/sslcerts.html
(I omitted the three lines of explanatory text that follow, and the file path and Bun version line at the end of the Bun error output below.)
The same happens when connecting from Bun's fetch. In the client.ts below, I put a call that does not pass the CA next to a call that passes the CA via tls.ca.
// How Bun's fetch behaves when the server uses a certificate from a CA you created yourself
const url = "https://localhost:8443/";
try {
const res = await fetch(url);
console.log("ca なし:", res.status, await res.text());
} catch (e) {
const err = e as Error & { code?: string };
console.log("ca なし: エラー", err.code, "-", err.message);
}
const res = await fetch(url, {
tls: { ca: Bun.file("./certs/ca.pem") },
});
console.log("ca あり:", res.status, await res.text());
The call without the CA failed, and the call with the CA returned 200.
$ bun client.ts
ca なし: エラー UNABLE_TO_VERIFY_LEAF_SIGNATURE - unable to verify the first certificate
ca あり: 200 こんにちは。https: でつながっています
Also, when I accessed the HTTPS port with http://, no response came back.
$ curl -sS http://localhost:8443/
curl: (52) Empty reply from server
Passing a file path as a string causes an error at startup
If you pass a string to key or cert, Bun reads it as the PEM contents. When I wrote file paths as strings, startup stopped right there.
// Mistake: passing file paths as strings
const server = Bun.serve({
port: 8444,
tls: {
key: "./certs/key.pem",
cert: "./certs/cert.pem",
},
fetch: () => new Response("ok\n"),
});
console.log(`起動しました: ${server.url}`);
$ timeout 5 bun path.ts
1 | // Mistake: passing file paths as strings
2 | const server = Bun.serve({
^
error: error:0900006e:PEM routines:OPENSSL_internal:NO_START_LINE
library: "PEM routines",
function: "OPENSSL_internal",
reason: "NO_START_LINE",
code: "ERR_OSSL_PEM_NO_START_LINE"
This NO_START_LINE error appeared when I passed a string that was not PEM contents. If you see this error, check whether you forgot to wrap the value with Bun.file(). The official documentation says you can pass a string, a BunFile, a Buffer, a TypedArray, or an array of these.
Open a passphrase-protected key with passphrase
If the private key is encrypted with a passphrase, pass the value to passphrase, as the official passphrase documentation explains. For the test, I made key-enc.pem by encrypting the same key as key.pem with openssl pkey -aes256, and read the passphrase from an environment variable.
openssl pkey -in key.pem -aes256 -passout pass:neko-pass -out key-enc.pem
// Use a key encrypted with a passphrase. Read it from the TLS_PASSPHRASE environment variable
const server = Bun.serve({
port: 8445,
tls: {
key: Bun.file("./certs/key-enc.pem"),
cert: Bun.file("./certs/cert.pem"),
passphrase: process.env.TLS_PASSPHRASE,
},
fetch: () => new Response("passphrase ok\n"),
});
console.log(`起動しました: ${server.url}`);
Startup failed with the same BAD_DECRYPT error both when TLS_PASSPHRASE was not set and when it was set to a wrong value. The error message alone does not tell you whether the passphrase was missing or wrong.
$ env TLS_PASSPHRASE=wrong timeout 5 bun passphrase.ts
1 | // Use a key encrypted with a passphrase. Read it from the TLS_PASSPHRASE environment variable
2 | const server = Bun.serve({
^
error: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT
library: "Cipher functions",
function: "OPENSSL_internal",
reason: "BAD_DECRYPT",
code: "ERR_OSSL_BAD_DECRYPT"
When I started the server with the correct passphrase (TLS_PASSPHRASE=neko-pass), it responded.
$ curl -sS --cacert certs/ca.pem https://localhost:8445/
passphrase ok
Select a certificate per hostname on one port
If you pass an array to tls and set serverName on each entry, the certificate switches based on the hostname the client sends during the TLS connection (SNI) (official SNI documentation). I created certificates for a.example.com and b.example.com with the same test CA and tested them.
// Return a different certificate for each hostname on one port (SNI)
const server = Bun.serve({
port: 8446,
tls: [
{
serverName: "a.example.com",
key: Bun.file("./certs/a-key.pem"),
cert: Bun.file("./certs/a-cert.pem"),
},
{
serverName: "b.example.com",
key: Bun.file("./certs/b-key.pem"),
cert: Bun.file("./certs/b-cert.pem"),
},
],
fetch(req) {
return new Response(`Host: ${req.headers.get("host")}\n`);
},
});
console.log(`起動しました: ${server.url}`);
I used curl's --resolve to send each hostname to 127.0.0.1. Each hostname got a different certificate (subject).
$ curl -sSv --cacert certs/ca.pem --resolve a.example.com:8446:127.0.0.1 https://a.example.com:8446/ 2>&1 | grep -E 'subject:|curl:|^Host'
* subject: CN=a.example.com
Host: a.example.com:8446
$ curl -sSv --cacert certs/ca.pem --resolve b.example.com:8446:127.0.0.1 https://b.example.com:8446/ 2>&1 | grep -E 'subject:|curl:|^Host'
* subject: CN=b.example.com
Host: b.example.com:8446
When I accessed c.example.com, which matches neither entry, in this test the server returned the certificate for a.example.com, the first entry in the array. curl stopped because the hostname did not match.
$ curl -sSv --cacert certs/ca.pem --resolve c.example.com:8446:127.0.0.1 https://c.example.com:8446/ 2>&1 | grep -E 'subject:|curl:|^Host'
* subject: CN=a.example.com
curl: (60) SSL: no alternative certificate subject name matches target host name 'c.example.com'
Forward requests that arrive over http:// to https://
As shown earlier, the HTTPS port gets no response to http:// requests. So I started a second Bun.serve for HTTP and redirected to the https:// URL. Only the protocol and port of new URL(req.url) are rewritten, so the path and query string stay the same.
// HTTPS server, plus a server that redirects requests arriving over http:// to https://
const https = Bun.serve({
port: 8443,
tls: {
key: Bun.file("./certs/key.pem"),
cert: Bun.file("./certs/cert.pem"),
},
fetch: () => new Response("HTTPS のページです\n"),
});
const http = Bun.serve({
port: 8080,
fetch(req) {
const url = new URL(req.url);
url.protocol = "https:";
url.port = String(https.port);
return Response.redirect(url.toString(), 301);
},
});
console.log(`HTTPS: ${https.url}`);
console.log(`HTTP : ${http.url}`);
When I accessed http://localhost:8080/cats?page=2, it returned a 301 redirect to https://localhost:8443/cats?page=2. Following the redirect with curl's -L returned the response from the HTTPS server.
$ curl -si http://localhost:8080/cats\?page=2
HTTP/1.1 301 Moved Permanently
Location: https://localhost:8443/cats?page=2
Date: Sat, 21 Nov 2026 23:21:18 GMT
Content-Length: 0
$ curl -sSL --cacert certs/ca.pem -w \[%\{http_code\}\]\ %\{url_effective\}\\n http://localhost:8080/cats\?page=2
HTTPS のページです
[200] https://localhost:8443/cats?page=2
Add http2: true to accept HTTP/2
When I accessed the first server.ts with curl, the server responded with HTTP/1.1 even though curl offered HTTP/2 (h2). According to the official HTTP/2 documentation, adding http2: true makes the server respond with HTTP/2 to clients that offer h2 in the TLS connection's ALPN negotiation. The documentation marks this feature as experimental.
// Adding http2: true lets HTTPS also accept HTTP/2 (experimental according to the official docs)
const server = Bun.serve({
port: 8447,
http2: true,
tls: {
key: Bun.file("./certs/key.pem"),
cert: Bun.file("./certs/cert.pem"),
},
fetch: () => new Response("h2 ok\n"),
});
console.log(`起動しました: ${server.url}`);
curl connected over HTTP/2, and with --http1.1 it used HTTP/1.1.
$ curl -sv --cacert certs/ca.pem https://localhost:8447/ 2>&1 | grep -E 'ALPN|using HTTP|^< HTTP|h2 ok'
* ALPN: curl offers h2,http/1.1
* ALPN: server accepted h2
* using HTTP/2
< HTTP/2 200
h2 ok
$ curl -sS --http1.1 --cacert certs/ca.pem -o /dev/null -w %\{http_version\}\\n https://localhost:8447/
1.1
Compare the time per new connection with HTTP
With TLS, every new connection includes an exchange of keys and other setup (the handshake). To see how much time this adds, I used curl to open 20 new connections each to server.ts (HTTPS) and a similar server without tls (HTTP), and measured the times. As the curl -w documentation explains, time_appconnect is the time from the start until the TLS handshake finishes.
| Average connection time (time_connect) | Average TLS completion (time_appconnect) | Average total (time_total) | Median total | |
|---|---|---|---|---|
| HTTPS | 0.075 ms | 3.643 ms | 3.951 ms | 3.563 ms |
| HTTP | 0.090 ms | none | 0.377 ms | 0.362 ms |
On localhost in my test environment, the median total showed that HTTPS took about 3.6 ms per new connection, roughly ten times the HTTP median of about 0.36 ms. Most of the difference came from the TLS handshake time. These numbers come from a single run of 20 connections each on localhost, so the times over a real network will be different.





