esBuild serve over HTTPS

1.5k Views Asked by At

esBuild makes it pretty easy to serve http requests over it's own dev server, e.g.

require('esbuild').serve({
  servedir: 'www',
}, {
  entryPoints: ['src/app.js'],
  outdir: 'www/js',
  bundle: true,
}).then(server => {
  // Call "stop" on the web server to stop serving
  server.stop()
})

How do I enable HTTPS serving in this case? I can make it serve on port 443, but how do I attach a self-signed certificate?

1

There are 1 best solutions below

0
On

I've found two solutions, that worked for me:

  1. using http-proxy, in an extra file or inside your esbuild config. The limitation I've found here, you cannot use esbuild's --serve and --watch together (https://github.com/evanw/esbuild/issues/805), so if you need auto reload/live server functionality, you have to create this on your own, which is slightly complicated (https://github.com/evanw/esbuild/issues/802)

    httpProxy.createServer({
      target: {
        host: 'localhost',
        port: 3000
      },
      ssl: {
        key: fs.readFileSync('key.pem', 'utf8'),
        cert: fs.readFileSync('cert.pem', 'utf8')
      }
    }).listen(3001);
    
  2. Using servor, here with npm scripts only, but you can also use servor in an esbuild config. Be aware to name your certificate files servor.crt and servor.key (https://github.com/lukejacksonn/servor/issues/79). I prefer this solution because of even less dependencies, simpler setup and auto reload/live server already build in.

    "scripts": {
      "build": "esbuild --bundle src/index.tsx --outfile=public/bundle.js",
      "start": "npm run server & npm run build -- --watch",
      "server": "servor public index.html 3000 --reload --secure"
    }