serve proxy with http2 possible?
I've found the instructions for setup a serve proxy: https://esbuild.github.io/api/#serve-proxy
But instead node:http I'd like to use node:http2 with http2, so I've changed the code a little and using http2.createSecureServer. I can start my bundler script without errors but all webbrowser complaining about the ssl certificate. Does anyone using http2 with esbuild and can point me to some example code?
https://nodejs.org/api/http2.html#http2createsecureserveroptions-onrequesthandler
I just tried it out. It looks like the sample code needed to get this to work is pretty much the same:
import * as esbuild from 'esbuild'
import http2 from 'node:http2'
import http from 'node:http'
import fs from 'node:fs'
// Start esbuild's server on a random local port
let ctx = await esbuild.context({
// ... your build options go here ...
})
// The return value tells us where esbuild's local server is
let { host, port } = await ctx.serve({ servedir: '.' })
// Then start a proxy server on port 3000
http2.createServer({
key: fs.readFileSync('your.key'),
cert: fs.readFileSync('your.cert'),
}, (req, res) => {
const options = {
hostname: host,
port: port,
path: req.url,
method: req.method,
headers: Object.fromEntries(
Object.entries(req.headers)
.filter(x => x[0][0] !== ':')),
}
// Forward each incoming request to esbuild
const proxyReq = http.request(options, proxyRes => {
// If esbuild returns "not found", send a custom 404 page
if (proxyRes.statusCode === 404) {
res.writeHead(404, { 'Content-Type': 'text/html' })
res.end('<h1>A custom 404 page</h1>')
return
}
// Otherwise, forward the response from esbuild to the client
res.writeHead(proxyRes.statusCode, proxyRes.headers)
proxyRes.pipe(res, { end: true })
})
// Forward the body of the request to esbuild
req.pipe(proxyReq, { end: true })
}).listen(3000)
all webbrowser complaining about the ssl certificate
I assume you're using a self-signed certificate. These complaints are an intentional part of how browsers work, and are a normal part of the process. That's why ignoring these complaints is one of the steps for enabling HTTPS in esbuild's documentation:
- Click past the scary warning in your browser when you load your page (self-signed certificates aren't secure, but that doesn't matter since we're just doing local development).
You can also use https://redirectto.me/ to have a valid SSL cert for your localhost. (this can be interesting if you would like to test your locally hosted builds on other devices where you can't bypass the certificate check)