Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How does Bun's bundler integrate with HTTP APIs


How does Bun's bundler integrate with HTTP APIs


Bun's bundler integrates seamlessly with HTTP APIs, providing a streamlined developer experience:

Bundler Output as HTTP Response

The bundler returns an array of `BuildArtifact` objects, which implement the `Blob` interface. These artifacts can be passed directly into HTTP APIs like `new Response()`, allowing you to serve bundled assets over HTTP with minimal effort[1].

js
const { files } = await Bun.build({
  entrypoints: ['./index.tsx'],
  outdir: './build',
});

return new Response(files['index.js'], {
  headers: { 'Content-Type': 'application/javascript' },
});

Automatic Serving of Bundled Assets

Bun plans to integrate the bundler with its built-in HTTP server API (`Bun.serve`) in an upcoming release. This will enable representing complex build pipelines with a simple declarative API[1]:

js
new Bun.App({
  configs: [
    {
      name: 'simple-http',
      target: 'bun',
      outdir: './.build/server',
    },
  ],
  routers: [
    {
      mode: 'static',
      dir: './public',
      build: 'simple-http',
    },
  ],
});

Standalone Executable Servers

The bundler can generate standalone executables from TypeScript and JavaScript scripts via the `--compile` flag. These executables are self-contained and include a copy of the Bun runtime, making them easy to deploy as HTTP servers[1][2].

bash
await Bun.build({
  entrypoints: ['./index.js'],
  outdir: './out',
  target: 'bun',
});

bash
./out/index

In summary, Bun's bundler is designed to integrate seamlessly with HTTP APIs, allowing you to serve bundled assets directly, automatically serve static assets, and generate standalone executable servers. This tight integration simplifies the development and deployment of web applications.

Citations:
[1] https://bun.sh/blog/bun-bundler
[2] https://www.infoworld.com/article/2338610/bundling-with-the-bunjs-bundler.html
[3] https://developer.mozilla.org/en-US/blog/leveraging-bun-on-vultr-a-superior-node-js-alternative/
[4] https://bun.sh/docs/bundler
[5] https://codesphere.com/articles/migrating-node-js-to-bun-is-it-really-a-drop-in-replacement
[6] https://bun.sh/docs/bundler/loaders
[7] https://www.builder.io/blog/bun-vs-node-js
[8] https://bun.sh.cn/docs/runtime/web-apis