Skip to content

CORS

The cors feature in LightTs enables Cross-Origin Resource Sharing (CORS), letting your API handle requests from web clients across domains.

  1. Run the Command

    Terminal window
    lts add cors
  2. Apply Middleware

    Use the generated middleware in index.ts.

src/core/cors.core.ts
import { app } from '@/config';
const originsList = [app.url];
...
export function checkCorsOrigin(
origin: string | undefined,
callback: (error: any, state: boolean) => void
) {
if (!origin) return callback(null, true); // for * origins
const origins = Object.values(originsList);
let result = origins.find((url) =>
typeof url === 'string' ? extractHostname(url) == extractHostname(origin) : null
);
if (result || !origin) {
callback(null, true);
} else {
callback(
`The CORS policy for this site does not allow access from the specified Origin.(${origin})`,
false
);
}
}
  • Customize origin to restrict domains (e.g., ['http://example.com']).
  • Adjust methods and allowedHeaders as needed.