In this post, we’ll look at how you can perform SvelteKit GraphQL queries using fetch only. That's right, there's no need to add Apollo client or urql to your Svelte apps if you have basic GraphQL requirements. We will get our GraphQL data from the remote API using just fetch functionality. You probably already know that the fetch API is available in client code . In SvelteKit, it is also available in load functions and server API routes. This means you can use the code we produce here to make GraphQL queries directly from page components or any server route.
caption="SvelteKit GraphQL Queries: What we're Building"
We will use a currency API to pull the latest exchange rates for a few currencies, querying initially from a server API route. This will be super useful for a backend dashboard on your platform. You can use it to track payments received in foreign currencies, converting them back to your local currency, be that dollars, rupees, euros, pounds, or even none of those! This will be so handy if you are selling courses, merch, or even web development services globally . Once the basics are up and running, we will add another query from a client page and see how easy Svelte stores make it to update your user interface with fresh data.
If that all sounds exciting to you, then let’s not waste any time!
We will be using the SWOP GraphQL API to pull the latest available currency exchange rates. To use the service, we will need an API key. There is a free developer tier, and they only ask for an email address when signing up. Let's go to the sign-up page now, sign up , confirm our email address and then make a note of our new API key.
.env file in the project root folder containing your API
With the preliminaries out of the way, let’s write our query.
To create a GraphQL query using fetch, basically all you need to do is create a query object and a
variables object, convert them to a string and then send them as the body to the right API
endpoint. We will use
fetch to do the sending as it is already
included in SvelteKit though you could choose
axios or some other
package if you wanted to. In addition to the body, we need to make sure we include the right auth
headers (as you would with Apollo client or urql).
That’s enough theory. If you want to do some more reading, Jason Lengstorf from Netlify wrote a fantastic article with plenty of extra details.
Let’s write some code. Create a file at
and paste in the following code:
You can see in lines
21 we define the GraphQL query. This uses regular GraphQL syntax. Just below, we define our query
variables. If you are making a different query which does not need any variables, be sure to
include an empty variables object.
30 you see we make a fetch request to the SWOP API.
Importantly, we include the
Content-Type header, set to
application/json in line
33. The rest of the file just processes the response
and relays it to the client.
Let’s create a store to save retrieved data next.
We will create a store as our “single source of truth”. Stores are an idiomatic, Svelte way of sharing app state between components. We won't go into much detail here, and you can learn more about Svelte stores in the Svelte tutorial .
To build the store, all we need to do is create the following file. Let's do that now, pasting the
content below into
src/lib/shared/stores/rates.ts (you will need
to create new folders):
Next, we can go client side to make use of SvelteKit GraphQL queries using fetch only.
We are using TypeScript in this project, but very little, so hopefully you can follow along even
though you are not completely familiar with TypeScript. Replace the content of
src/routes/+page.svelte with the following:
export let data in line
telling SvelteKit to source the
data parameter from the page load
function (we will create this in a moment). This contains the initial rate data we got from the
3, we import the store we just created. Next, we actually
make use of the store. We add the query result to the store in line
16. We will actually render whatever is in the store, rather than the result of the query
directly. The benefit of doing it that way is that we can easily update what is rendered by adding
another other currency pair to the store (without any complex logic for merging what is already
rendered with new query results). You will see this shortly.
This should all work as is. Optionally add a little style before continuing:
src/routes/+page.svelte — click to expand code.
OK, let’s take a peek at what we have so far by going to
Finally, we will look at how updating the store updates the user interface. We already have a form
48), but it is not yet wired up. We
already have a
name attribute set on the input. We can use this,
now, in our action code, to pull in whatever the user enters. Update
27, we read in the form data, identifying the field we need using the value of its name field (
currency). After that, the code is not that different from the load function that already existed in
this file. The main difference is that we query for and return a single rate, rather than an array
of rates, as in the load function.
We need to read this in the client, Svelte, file. Update
src/routes/+page.svelte with these lines so, once the user submits the form, we trigger a store update:
Try this out yourself, adding a couple of currencies. The interface should update straight away.
In this post, we learned:
- how to do SvelteKit GraphQL queries using fetch instead of Apollo client or urql,
- a way to get up-to-date currency exchange rate information into your site backend dashboard for analysis, accounting, and so many other uses,
- how stores can be used in Svelte to update state.
See the follow-up post in which we automatically generate TypeScript types for the GraphQL API. Type generation is not too onerous in this example, though you can see how to do it automatically for more intricate GraphQL APIs, getting free autocompletion and help to spot code errors.
There are some restrictions on the base currency in SWOP's developer mode. The maths (math) to convert from EUR to the desired base currency isn't too complicated, though. You could implement a utility function to do the conversion in the API route file. If you do find the service useful, or and expect to use it a lot, consider supporting the project by upgrading your account.
As an extension you might consider pulling historical data from the SWOP API, this is not too different, to the GraphQL query above. Have play in the SWOP GraphQL Playground to discover more of the endless possibilities . Finally, you might also find the Purchasing Power API handy if you are looking at currencies. This is not a GraphQL API, though it might be quite helpful for pricing your courses in global economies you are not familiar with.
Is there something from this post you can leverage for a side project or even client project? I hope so! Let me know if there is anything in the post that I can improve on, for anyone else creating this project. You can leave a comment below, @ me on Twitter or try one of the other contact methods listed below.
- SvelteKit makes fetch available in load functions and on endpoints. This is a great alternative to Apollo Client and urql when you want to get up and running quickly on your new project. Although you won't have access to the caching features provided by Apollo Client and urql if you use just fetch, SvelteKit does make it easy to create a cache using stores. The advantages of using fetch are you keep your app lighter, with fewer dependencies, and also that the API is very stable. This saves you refactoring code as APIs change.
- Using fetch for GraphQL queries is as simple as creating a query and variables object and sending those to your endpoint. In the case your query does not need any variables, you will still need to include an albeit empty variable object in the request. The query variable is the GraphQL query (or mutation) using regular GraphQL syntax, as a string. We use the POST method to send the query to our external API. Importantly, we include the 'Content-Type': 'application/json' HTTP header in the request.
- In this tutorial, we run through an example using an FX rate GraphQL API to fetch data. We make GraphQL calls both from the client code and our API endpoints. There is also a link to the complete tutorial project code on GitHub at the bottom of the article. You can follow along, building the project out yourself, or just jump straight to the GitHub repo.
Have you found the post useful? Do you have your own methods for solving this problem? Let me know your solution. Would you like to see posts on another topic instead? Get in touch with ideas for new posts. Also, if you like my writing style, get in touch if I can write some posts for your company site on a consultancy basis. Read on to find ways to get in touch, further below. If you want to support posts similar to this one and can spare a few dollars, euros or pounds, please consider supporting me through Buy me a Coffee.
🔥 Here's something to help you keep your SvelteKit GraphQL apps lean.— Rodney (@askRodney) September 27, 2021
See how you can query
#GraphQL endpoints using just fetch... no urql, no Apollo client!
Also handle state with ❤️ Svelte stores.
Hope you find this useful!https://t.co/D1rLmh229H #sveltekit @SvelteSociety pic.twitter.com/087gRALZxq
Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on Twitter and also askRodney on Telegram . Also, see further ways to get in touch with Rodney Lab. I post regularly on SvelteKit as well as other topics. Also, subscribe to the newsletter to keep up-to-date with our latest projects.