Overview

Enable cross-origin requests with configurable options.

Features

  • Origin whitelist
  • Credentials support
  • Methods config
  • Environment-driven

Installation

npx hanma add elysia-cors --framework elysia

Dependencies

@elysiajs/cors

Code

import type { Elysia } from "elysia";
import { cors } from "@elysiajs/cors";

/**
 * CORS configuration for Elysia
 * Reads origins from environment variable for production safety
 */
export const setupCors = <T extends Elysia>(app: T) => {
  const allowedOrigins = process.env.CORS_ORIGINS
    ? process.env.CORS_ORIGINS.split(",").map((origin) => origin.trim())
    : ["http://localhost:3000", "http://localhost:5173"];

  return app.use(
    cors({
      origin: allowedOrigins,
      methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
      allowedHeaders: ["Content-Type", "Authorization", "X-Request-ID"],
      credentials: true,
      maxAge: 86400, // 24 hours
    })
  );
};

/* USAGE:

import { Elysia } from "elysia";
import { setupCors } from "./plugins/cors";

const app = new Elysia();
setupCors(app);

// Or inline:
app.use(setupCors);

*/

Usage

import { setupCors } from './plugins/cors';

app.use(setupCors);

Dependencies

Frequently Asked Questions

How do I install CORS Plugin?
Run the following command: npx hanma add elysia-cors --framework elysia
What dependencies are required?
This snippet requires: @elysiajs/cors. Make sure to install them before using the snippet.
How do I use this snippet?
Copy the code and paste it into your project. The snippet will be saved to src/plugins/cors.ts.
Can I customize this snippet?
Yes! All snippets are copy-paste code that you own. Feel free to modify them to fit your needs.
Does this work with other frameworks?
This snippet is designed for the specific framework. Check the other framework pages for equivalent implementations.