Public API & CORS Requests

Last updated 9 days ago

Building an Open API requires to allow Cross-Origin Request Sharing.

Enable Cross-Origin Resource Sharing (CORS)

If you are building a web application, you may not need to enable CORS for your API. See here the section Origins that Do not Match.

If you want different origins to make requests to your API from a browser, you need to enable Cross-Origin Resource Sharing.

You can do that by adding a route handler and a special hook to your API root controller (APIController in this example).

@Hook(() => (ctx, services, response) => {
// Every response of this controller and its sub-controllers will be added this header.
response.setHeader('Access-Control-Allow-Origin', '*');
export class ApiController {
subControllers = [
// your sub-controllers
options(ctx: Context) {
const response = new HttpResponseNoContent();
// You may need to allow other headers depending on what you need.
response.setHeader('Access-Control-Allow-Headers', 'Content-Type');
return response;
// Some other routes (ex: @Get('/users'), etc)