@bklarjs/cors
v1.0.1
Published
CORS middleware for the bklar framework.
Downloads
19
Maintainers
Readme
@bklarjs/cors 🌐
Official CORS (Cross-Origin Resource Sharing) middleware for the bklar framework.
This package enables your bklar application to handle requests from different origins, which is essential for building modern web applications where the frontend and backend are hosted on separate domains.
✨ Features
- 🧩 Simple Integration: Enable CORS for your entire application with a single line of code.
- 🔧 Flexible Configuration: Easily configure allowed origins, methods, headers, and more to fit your security requirements.
- ⚙️ Automatic Preflight Handling: Automatically handles complex
OPTIONS(preflight) requests without any extra effort. - 🔒 Sensible Defaults: Comes with permissive defaults for a quick and easy setup during development.
- 🛡️ Full TypeScript Support: Strongly-typed configuration options for a better development experience.
📦 Installation
This package is designed to work with bklar. You'll need both installed in your project.
bun add bklar @bklarjs/cors🚀 Usage
The most common way to use this middleware is to apply it globally to your application.
1. Basic Usage (Development)
For local development, you can enable CORS with its default, permissive settings. This will allow requests from any origin.
import { Bklar } from "bklar";
import { cors } from "@bklarjs/cors";
const app = Bklar();
// Apply the CORS middleware globally
app.use(cors());
app.get("/", (ctx) => {
return ctx.json({ message: "CORS is enabled!" });
});
app.listen(3000);2. Production Configuration (Secure)
For production, you should always restrict which origins are allowed to access your API.
import { Bklar } from "bklar";
import { cors } from "@bklarjs/cors";
const app = Bklar();
app.use(
cors({
// Allow a specific frontend origin
origin: "https://my-awesome-frontend.com",
// Allowed HTTP methods
methods: ["GET", "POST", "PUT", "DELETE"],
// Allow the frontend to send credentials (e.g., cookies)
credentials: true,
// Cache preflight response for 1 day (in seconds)
maxAge: 86400,
})
);
app.get("/api/data", (ctx) => {
return ctx.json({ data: "This is protected by CORS" });
});
app.listen(3000);⚙️ Configuration Options
The cors() factory accepts an options object:
origin: (Required) Configures theAccess-Control-Allow-Originheader.true: Allows any origin.string: Allows a single, specific origin (e.g.,'https://example.com').string[]: Allows a list of specific origins.RegExp: Allows origins matching a regular expression.(string | RegExp)[]: Allows a mixed list of specific origins and regular expressions.
methods: An optionalstringorstring[]of allowed HTTP methods. Defaults to'GET,HEAD,PUT,PATCH,POST,DELETE'.allowedHeaders: An optionalstringorstring[]of allowed request headers.exposedHeaders: An optionalstringorstring[]to configure theAccess-Control-Expose-Headersheader. This allows the client-side code to access custom headers you set in your responses.credentials: Aboolean. Iftrue, it sets theAccess-Control-Allow-Credentialsheader. Defaults tofalse.maxAge: Anumberthat sets theAccess-Control-Max-Ageheader in seconds. This specifies how long the results of a preflight request can be cached.
Example: Multiple Origins
You can easily allow multiple domains, which is useful for staging and production environments.
const allowedOrigins = [
"https://my-awesome-frontend.com",
"https://staging.my-awesome-frontend.com",
/localhost:\d{4}$/, // Allow localhost on any 4-digit port
];
app.use(cors({ origin: allowedOrigins }));🛠️ How It Works
This middleware inspects incoming requests for an Origin header.
- Preflight Requests (
OPTIONS): If the request method isOPTIONS, the middleware checks if the origin is allowed. If so, it responds immediately with a204 No Contentstatus and the appropriateAccess-Control-*headers, effectively ending the request cycle. - Actual Requests (e.g.,
GET,POST): For other requests, the middleware checks the origin and, if allowed, attaches the appropriateAccess-Control-Allow-Originheader to the final response sent by your route handler.
🧰 API Reference
This package exports the following:
cors(options: CorsOptions): Middleware: The main factory function that creates the CORS middleware.
🤝 Contributing
Contributions are welcome! Please open an issue or submit a Pull Request to the main bklar repository.
📄 License
This project is licensed under the MIT License.
