JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 9
  • Score
    100M100P100Q28817F
  • License ISC

Add basic or custom CORS headers to Bun routes

Package Exports

  • bun-routes-cors
  • bun-routes-cors/index.ts

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (bun-routes-cors) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

bun-routes-cors

drawing

CORS for the built-in routing (Bun.serve()):

A CORS module for the built-in router, which released in Bun version 1.2.3!

๐Ÿš€ Installation

bun i bun-routes-cors

โš ๏ธ Do not use "npm i"

๐Ÿงช Code example:

import CORS from "bun-routes-cors";

Bun.serve({
    port: 8080,
    development: true,
    routes : CORS({
        "/register": {
            POST: async (req: Bun.BunRequest<"/register">) => {
               // your code here...
            }
        },
        "/login": {
            POST: async (req: Bun.BunRequest) => {
                // your code here...
            }
        },
        "/test/:link" : {
            GET: async (req) => {
                return Response.json({});
            },
            POST: async (req: Bun.BunRequest<"/test/:link">) => {
                return new Response(`Hi! Your link parameter: ${req.params.link}`); 
                // to use req params pass type to "req" like this
            }
        }
    }, {    // optional: set your custom headers, these are the default values:
        origin: "*",  // 'yoursite.com'
        methods: "*", // 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD'
        headers: "*" // 'Content-Type', 'Authorization'
    })
});

Passing the second object is optional; if you don't specify the origin, methods, and headers values, everything is passed by default.

๐Ÿชถ Preflight

It also handles "preflight" requests, returning CORS headers you specify or implicitly, a null response value, and a 204 status.

new Response(null, {
    status: 204,
    headers: ...,
});

๐Ÿž Official Docs: https://bun.sh/docs/api/http#bun-serve

Supports all request types described in the docs!