SvelteKit GraphQL Queries using fetch Only # SvelteKit GraphQL Queries using fetch Only #
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.
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 install
When prompted choose a Skeleton Project and answer Yes to TypeScript, ESLint and Prettier.
API Key #
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.

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
:
1 import 'dotenv/config';2 import preprocess from 'svelte-preprocess';34 /** @type {import('@sveltejs/kit').Config} */5 const config = {6 // Consult https://github.com/sveltejs/svelte-preprocess7 // for more information about preprocessors8 preprocess: preprocess(),910 kit: {11 // hydrate the <div id="svelte"> element in src/app.html12 target: '#svelte'13 }14 };1516 export default config;
Finally, create a .env
file in the project root folder containing your
API key:
SWOP_API_KEY="0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
With the preliminaries out of the way let's write our query.
🗳 Poll #
🧱 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:
1 import type { Request } from '@sveltejs/kit';23 export 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;89 const query = `10 query latestQuery(11 $latestQueryBaseCurrency: String = "EUR"12 $latestQueryQuoteCurrencies: [String!]13 ) {14 latest(15 baseCurrency: $latestQueryBaseCurrency16 quoteCurrencies: $latestQueryQuoteCurrencies17 ) {18 baseCurrency19 quoteCurrency20 date21 quote22 }23 }24 `;2526 const variables = {27 latestQueryBaseCurrency: 'EUR',28 latestQueryQuoteCurrencies: currencies29 };3031 const response = await fetch('https://swop.cx/graphql', {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 variables40 })41 });42 const data = await response.json();4344 return {45 body: JSON.stringify({ ...data })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 error53 };54 }55 }
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):
1 import { writable } from 'svelte/store';23 const rates = writable([]);45 export { 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 };19 </script>2021 <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;30 </script>3132 <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>55 </main>
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.
57 <style>58 :global body {59 margin: 0px;60 }6162 .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 }7071 .content {72 margin: 3rem auto 1rem;73 width: 50%;74 border-radius: 1rem;75 border: #f7fff7 solid 1px;76 }7778 .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 }8788 h1 {89 color: #1a535c;90 }9192 ul {93 background: #1a535c;94 list-style-type: none;95 padding: 1.5rem;96 }9798 li {99 margin-bottom: 1.5rem;100 }101102 h2 {103 color: #ffe66d;104 margin-bottom: 0.5rem;105 }106107 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 }115116 .rate {117 font-size: 1.25rem;118 }119 dt {120 flex-basis: 15%;121 padding: 2px 0.25rem;122 }123124 dd {125 flex-basis: 80%;126 flex-grow: 1;127 padding: 2px 0.25rem;128 }129130 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 }155156 .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 }167168 @media (max-width: 768px) {169 .content,170 form,171 .heading {172 width: auto;173 margin: 1.5rem;174 }175 }176 </style>
Ok let's take a peek at what we have so far by going to localhost:3000/ .

🚀 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;3031 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 = responseData.data.latest[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 }51 </script>5253 <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>7677 <form on:submit|preventDefault={handleSubmit}>78 <span class="screen-reader-text"79 ><label for="additional-currency">Additional Currency</label></span80 >81 <input82 bind:value={newCurrency}83 required84 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>91 </main>
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.
Extensions #
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: Summary #
Do you need to use Apollo Client or URQL to run GraphQL queries in SvelteKit? #
- 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 you app lighter, with fewer dependencies and also that the API is very stable. This saves you refactoring code as APIs change.
How do you use fetch for GraphQL queries in SvelteKit? #
- 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.
Where can I find some example code using fetch for GraphQL queries in SvelteKit? #
- 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 out 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.
🙏🏽 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.
