SvelteKit GraphQL Queries using fetch Only

SvelteKit GraphQL Queries

SvelteKit GraphQL Queries using fetch Only


πŸ˜• Why drop Apollo Client and urql for GraphQL Queries?

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.

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 an additional 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!

βš™οΈ SvelteKit GraphQL Queries: Setup

We'll start by creating a new project and installing packages:

pnpm init [email protected] sveltekit-graphql-fetch && cd $_
pnpm install

When prompted choose a Skeleton Project and answer Yes to TypeScript, ESLint and Prettier.

SvelteKit GraphQL Queries: Setup


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 you only need an email address to sign 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.

SvelteKit GraphQL Queries: Getting an API Key.  Sign up form for API key.  Title is Getting Started.  There are boxes to enter an email address and password as well as a start now submit button.  Additional information includes a statement that no credit card is required.  There is a checkbox to agree to the Terms and Conditions.  Finally there is a link to sign if if you already have an account
SvelteKit GraphQL Queries: Getting an API Key

Configuring dotenv

Let's configure dotenv now so we can start using the API quick sticks. Install the dotenv package and the following font which we will use later:

pnpm install -D dotenv @fontsource/source-sans-pro

Next edit svelte.config.js to use dotenv:

1import 'dotenv/config';
2import preprocess from 'svelte-preprocess';
4/** @type {import('@sveltejs/kit').Config} */
5const config = {
6 // Consult
7 // for more information about preprocessors
8 preprocess: preprocess(),
10 kit: {
11 // hydrate the <div id="svelte"> element in src/app.html
12 target: '#svelte'
13 }
16export default config;

Finally, create a .env file in the project root folder containing your API key:


With the preliminaries out of the way let's write our query.

πŸ—³οΈ Poll

What do you normally use for GraphQL client queries?
Voting reveals latest results.

🧱 API Route

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 src/routes/query/fx-rates.json.ts and paste in the following code:

1import type { Request } from '@sveltejs/kit';
3export async function post(
4 request: Request & { body: { currencies: string[] } }
5): Promise<{ body: string } | { error: string; status: number }> {
6 try {
7 const { currencies = ['CAD', 'GBP', 'IDR', 'INR', 'USD'] } = request.body;
9 const query = `
10 query latestQuery(
11 $latestQueryBaseCurrency: String = "EUR"
12 $latestQueryQuoteCurrencies: [String!]
13 ) {
14 latest(
15 baseCurrency: $latestQueryBaseCurrency
16 quoteCurrencies: $latestQueryQuoteCurrencies
17 ) {
18 baseCurrency
19 quoteCurrency
20 date
21 quote
22 }
23 }
24 `;
26 const variables = {
27 latestQueryBaseCurrency: 'EUR',
28 latestQueryQuoteCurrencies: currencies
29 };
31 const response = await fetch('', {
32 method: 'POST',
33 headers: {
34 'Content-Type': 'application/json',
35 Authorization: `ApiKey ${process.env['SWOP_API_KEY']}`
36 },
37 body: JSON.stringify({
38 query,
39 variables
40 })
41 });
42 const data = await response.json();
44 return {
45 body: JSON.stringify({ })
46 };
47 } catch (err) {
48 const error = `Error in /query/fx-rates.json.ts: ${err}`;
49 console.error(error);
50 return {
51 status: 500,
52 error
53 };
54 }

What this Code Does

This is code for a fetch API route making use of SvelteKit's router. To invoke this code from a client, we just send a POST request to /query/fx-rates.json with that path being derived from the file's path. We will do this together shortly, so just carry on if this is not yet crystal clear.

You can see in lines 9–24 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.

In line 31 you see we make a fetch request to the SWOP API. Importantly, we include the Content-Type header, set to application/json in line 34. The rest of the file just processes the response and relays it back to the client.

Let's create a store to save retrieved data next.

πŸ›οΈ Store

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):

1import { writable } from 'svelte/store';
3const rates = writable([]);
5export { rates as default };

Next, we can go client side to make use of SvelteKit GraphQL queries using fetch only.

πŸ–₯ Initial Client Code: SvelteKit GraphQL queries using fetch

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/index.svelte with the following:

1<script context="module">
2 export const load = async ({ fetch }) => {
3 try {
4 const response = await fetch('/query/fx-rates.json', {
5 method: 'POST',
6 credentials: 'same-origin',
7 headers: {
8 'Content-Type': 'application/json'
9 },
10 body: JSON.stringify({ currencies: ['CAD', 'GBP', 'IDR', 'INR', 'USD'] })
11 });
12 return {
13 props: { ...(await response.json()) }
14 };
15 } catch (error) {
16 console.error(`Error in load function for /: ${error}`);
17 }
18 };
21<script lang="ts">
22 import '@fontsource/source-sans-pro';
23 import rates from '$lib/shared/stores/rates';
24 export let data: {
25 latest: { baseCurrency: string; quoteCurrency: string; date: Date; quote: number }[];
26 };
27 rates.set(data.latest);
28 let newCurrency = '';
29 let submitting = false;
32<main class="container">
33 <div class="heading">
34 <h1>FX Rates</h1>
35 </div>
36 <ul class="content">
37 {#each $rates as { baseCurrency, quoteCurrency, date, quote }}
38 <li>
39 <h2>{`${baseCurrency}\${quoteCurrency}`}</h2>
40 <dl>
41 <dt>
42 {`1 ${baseCurrency}`}
43 </dt>
44 <dd>
45 <span class="rate">
46 {quote.toFixed(2)}
47 {quoteCurrency}
48 </span>
49 <details><summary>More information...</summary>Date: {date}</details>
50 </dd>
51 </dl>
52 </li>
53 {/each}
54 </ul>

With TypeScript you can define variable types alongside the variable. So in line 25, we are saying that data is an object with a single field; latest. latest itself is an array of objects (representing currency pairs in our case). Each of these objects has the following fields: baseCurrency, quoteCurrency, date and quote. You see the type of each of these declared alongside it.

What are we Doing Here?

The first <script> block contains a load function. In SvelteKit, load functions contain code which runs before the initial render. It makes sense to call the API route we just created from here. We do that using the fetch call in lines 4–11. Notice how the url matches the file path for the file we created. The JSON response is sent as a prop (from the return statement in lines 12–14).

Another interesting line comes in the second <script> block. Here at line 23, we import the store we just created. Line 24 is where we import the props we mentioned as a data prop. The types come from the object we expect the API to return. It is not too much hassle to type this out for a basic application like this one. For a more sophisticated app, you might want to generate types automatically. In a follow-up post, we see how you can generate the types automatically with graphql-codegen.

Next we actually make use of the store. We add the query result to the store in line 27. 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:

Optional Styling

src/routes/index.svelte β€” click to expand code.
58 :global body {
59 margin: 0px;
60 }
62 .container {
63 display: flex;
64 flex-direction: column;
65 background: #ff6b6b;
66 min-height: 100vh;
67 color: #1a535c;
68 font-family: 'Source Sans Pro';
69 }
71 .content {
72 margin: 3rem auto 1rem;
73 width: 50%;
74 border-radius: 1rem;
75 border: #f7fff7 solid 1px;
76 }
78 .heading {
79 background: #f7fff7;
80 text-align: center;
81 width: 50%;
82 border-radius: 1rem;
83 border: #1a535c solid 1px;
84 margin: 3rem auto 0rem;
85 padding: 0 1.5rem;
86 }
88 h1 {
89 color: #1a535c;
90 }
92 ul {
93 background: #1a535c;
94 list-style-type: none;
95 padding: 1.5rem;
96 }
98 li {
99 margin-bottom: 1.5rem;
100 }
102 h2 {
103 color: #ffe66d;
104 margin-bottom: 0.5rem;
105 }
107 dl {
108 background-color: #ffe66d;
109 display: flex;
110 margin: 0.5rem 3rem 1rem;
111 padding: 1rem;
112 border-radius: 0.5rem;
113 border: #ff6b6b solid 1px;
114 }
116 .rate {
117 font-size: 1.25rem;
118 }
119 dt {
120 flex-basis: 15%;
121 padding: 2px 0.25rem;
122 }
124 dd {
125 flex-basis: 80%;
126 flex-grow: 1;
127 padding: 2px 0.25rem;
128 }
130 form {
131 margin: 1.5rem auto 3rem;
132 background: #4ecdc4;
133 border: #1a535c solid 1px;
134 padding: 1.5rem;
135 border-radius: 1rem;
136 width: 50%;
137 }
138 input {
139 font-size: 1.563rem;
140 border-radius: 0.5rem;
141 border: #1a535c solid 1px;
142 background: #f7fff7;
143 padding: 0.25rem 0.25rem;
144 margin-right: 0.5rem;
145 width: 6rem;
146 }
147 button {
148 font-size: 1.563rem;
149 background: #ffe66d;
150 border: #1a535c solid 2px;
151 padding: 0.25rem 0.5rem;
152 border-radius: 0.5rem;
153 cursor: pointer;
154 }
156 .screen-reader-text {
157 border: 0;
158 clip: rect(1px, 1px, 1px, 1px);
159 clip-path: inset(50%);
160 height: 1px;
161 margin: -1px;
162 width: 1px;
163 overflow: hidden;
164 position: absolute !important;
165 word-wrap: normal !important;
166 }
168 @media (max-width: 768px) {
169 .content,
170 form,
171 .heading {
172 width: auto;
173 margin: 1.5rem;
174 }
175 }

Ok let's take a peek at what we have so far by going to localhost:3000/ .

SvelteKit GraphQL Queries: Story so Far.  Image shows top part of a screenshot of how the app should look now, with styling applied.  There is an FX Rates title and below a block containing two currency pair results: EUR\CAD and EUR\GBP.  Eash shows the value of 1 euro in the curreny and a More information link
SvelteKit GraphQL Queries: Story so Far

πŸš€ SvelteKit GraphQL queries using fetch: Updating the Store

Finally we will look at how updating the store updates the user interface We will add a form in which the user can add a new currency. Edit src/routes/index.svelte:

21<script lang="ts">
22 import '@fontsource/source-sans-pro';
23 import rates from '$lib/shared/stores/rates';
24 export let data: {
25 latest: { baseCurrency: string; quoteCurrency: string; date: Date; quote: number }[];
26 };
27 rates.set(data.latest);
28 let newCurrency = '';
29 let submitting = false;
31 async function handleSubmit() {
32 try {
33 submitting = true;
34 const response = await fetch('/query/fx-rates.json', {
35 method: 'POST',
36 credentials: 'same-origin',
37 headers: {
38 'Content-Type': 'application/json'
39 },
40 body: JSON.stringify({ currencies: [newCurrency] })
41 });
42 const responseData = await response.json();
43 const rate =[0];
44 submitting = false;
45 rates.set([...$rates, rate]);
46 newCurrency = '';
47 } catch (error) {
48 console.error(`Error in handleSubmit function on /: ${error}`);
49 }
50 }
53<main class="container">
54 <div class="heading">
55 <h1>FX Rates</h1>
56 </div>
57 <ul class="content">
58 {#each $rates as { baseCurrency, quoteCurrency, date, quote }}
59 <li>
60 <h2>{`${baseCurrency}\${quoteCurrency}`}</h2>
61 <dl>
62 <dt>
63 {`1 ${baseCurrency}`}
64 </dt>
65 <dd>
66 <span class="rate">
67 {quote.toFixed(2)}
68 {quoteCurrency}
69 </span>
70 <details><summary>More information...</summary>Date: {date}</details>
71 </dd>
72 </dl>
73 </li>
74 {/each}
75 </ul>
77 <form on:submit|preventDefault={handleSubmit}>
78 <span class="screen-reader-text"
79 ><label for="additional-currency">Additional Currency</label></span
80 >
81 <input
82 bind:value={newCurrency}
83 required
84 id="additional-currency"
85 placeholder="AUD"
86 title="Add another currency"
87 type="text"
88 />
89 <button type="submit" disabled={submitting}>Add currency</button>
90 </form>

In line 82 you see using Svelte it is pretty easy to link the value of an input to one of our TypeScript or javascript variables. We do this with the newCurrency variable here. In our handleSubmit function, we call our API route once more, this time only requesting the additional currency. In line 45 we see updating state is a piece of cake using stores. We just spread the current value of the rate store (this is nothing more than an array of the existing five currency objects) and tack the new one on the end.

Try this out yourself, adding a couple of currencies. The interface should update straight away.

πŸ™ŒπŸ½ SvelteKit GraphQL queries using fetch: What Do You Think?

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 ti automatically for more intricate GraphQL APIs, getting free autocompletion and help spotting 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 any one else creating this project. You can leave a comment below, @ me on Twitter or try one of the other contact methods listed below.

You can see the full code for this SvelteKit GraphQL queries using fetch project on the Rodney Lab Git Hub repo .

πŸ™πŸ½ SvelteKit GraphQL queries using fetch: Feedback

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.

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.