CORS
The cors
feature in LightTs enables Cross-Origin Resource Sharing (CORS), letting your API handle requests from web clients across domains.
Add CORS Support
Section titled “Add CORS Support”-
Run the Command
Terminal window lts add cors -
Apply Middleware
Use the generated middleware in
index.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 ); }}
...import { corsMiddleware } from '@/core/cors.core';
...
// corsapp.use( cors({ origin: checkCorsOrigin, credentials: true }));
...
- Customize
origin
to restrict domains (e.g.,['http://example.com']
). - Adjust
methods
andallowedHeaders
as needed.
See CORS in Action Try a CORS-enabled route example.