Sveltekit proxy api to avoid cors

Viewed 4829

I'm actually building a basic svelkit app. I need to fetch to a weather api but impossible to fetch I have cors errors : enter image description here

I guess I need to setup a proxy for https://www.metaweather.com is there any way to do it with svelte kit ?

1 Answers

There certainly is. SvelteKit routing provides two types of routes, pages (= frontend) and endpoints (= backend).

Quoting the SvelteKit routing docs:

Endpoints run only on the server (or when you build your site, if prerendering). This means it's the place to do things like access databases or APIs that require private credentials or return data that lives on a machine in your production network. Pages can request data from endpoints. Endpoints return JSON by default, though may also return data in other formats.

CORS is essentially a form of credentialed request, so having an endpoint acting as a proxy API is ideal.

This is what such a route would look like in your use case:

// src/routes/api/weather/[city].json.js
export async function get({ params }) {
    const { city } = params;

    const res = await fetch(`https://www.metaweather.com/api/location/search/?query=${city}`);
    const weather = await res.json();

    return { body: weather };    
}

SvelteKit Endpoints documentation detailing stuff like the expected format of the return object, handling POSTs requests, etc.

Once this route is up, you would access it in lieu of accessing the original API in your frontend code, for example:

fetch(`http://localhost:3000/api/weather/${city}.json`);

And that's pretty much all there is to it.

Important update for users of a newer release of SvelteKit

In newer releases of SvelteKit, following its switch to a slightly different routing convention, the endpoint above should now be located in src/routes/api/weather/[city].json/+server.js. Its content should still work as-is however.

Related