Matrix-like background

How to call an external API with valid CORS?

Have you ever needed to call a third party API that resides on a different domain? You probably had CORS issues.

The problem

I tested the LLM from Infomaniak the other day and I struggled with the CORS (Cross-Origin Resource Sharing) issue again.

It is a recurring issue when you host your app on the https://my-app.com and it requests an api on https://api.example.com.

The browser will prevent you from doing so unless the backend allows the frontend explicitly with the Access-Control-Allow-Origin header, hopefully not *.

MDN describes in detail the concept on their website.

The Solution

If you use Netlify, you can use two methods:

netlify.toml file

As this Netlify thread states, you need to define a rewrite rule:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# This is the rule to query the API without CORS
[[redirects]]
  from = "/api/*"
  to = "https://api.example.com/:splat"
  status = 200
  force = true

# This is the rule you set to handle soft 404 in your SPA
[[redirects]]
  from = "/*"
  to = "/index.html"
  status = 200

A _redirects File

This option is the same as above, but you write it differently:

1
2
/api-llm https://api.infomaniak.com/2/llm/701/chat/completions 200
/\* /index.html 200

Also, be sure to name the file _redirects and place it in the public directory.

Credits: Photo by Markus Spiske on Unsplash.

Licensed under CC BY-NC-SA 4.0
License GPLv3 | Terms
Built with Hugo
Theme Stack designed by Jimmy