MAIS AMOR POR FAVOR

Use Apollo Client with SvelteKit to Query a GraphQL API

Use Apollo Client with SvelteKit

Use Apollo Client with SvelteKit to Query a GraphQL API

SHARE:

Use Apollo Client with SvelteKit

In this post we look at how to use Apollo Client with SvelteKit. We will query the GitHub GraphQL API to pull out some data from your repos. If you are new to SvelteKit, you will find this post useful, as we use a few of SvelteKit's idiosyncrasies. These help Svelte offer an improved developer experience. If you come from a React background, then you might well already be familiar with Apollo Client, so I hope you can leverage that knowledge here to get to learn SvelteKit a little quicker. Instead of building yet another todo app, you will create some code in this tutorial which you can leverage to generate a Projects page on your personal developer blog.

Use Apollo Client with SvelteKit: What we're Building - screen capture showing an array of boxes stacked vertically. Each box contains details of a Git Hub repo such as name, number of stars and last updated date.
Getting Started with SvelteKit: What we're Building Screen Capture

To follow along, you might find a GitHub account useful. If you don't already have one, just hop over to github.com and click the Sign up for GitHub button . We won't look in too much detail at what GraphQL is here. You might be new to GraphQL, though that is not a barrier. You will find this Introduction to GraphQL useful . If you're ready let's get started.

🔧 GitHub GraphQL API

The GitHub GraphQL API let's you query your repo and other users' public repos. Here we will just be pulling data about your own repo, such as description, last commit and stars. You can use this code on your blog Projects page. Using GitHub to source the information you only ever have to update content in one place. You are kind of using GitHub as a Content Management System (CMS) for you Projects page. For sparkles, you could pull the repo code languages and tags, and, add filters so future employers can see exactly what you coded in each language. There is so much magic you can do with this API. Your imagination is the limit!

GitHub GraphQL API Explorer

You don't have to do this step for the tutorial, though you might find it interesting. GitHub has a GraphiQL explorer for the GitHub API . You can use it to check what GraphQL queries you can make as well as get documentation. If you are extending this project for you own needs, you can generate your queries and mutations in GraphiQL and then paste them into your code editor once you are happy with them. For the Explorer to work, you will need to Sign in to your account and then authorise it to access your GitHub account.

Use Apollo Client with SvelteKit: Getting a GitHub Personal Access Token

Although you don't need to authorise the Explorer get going on this project, you will need to generate a GitHub personal Access Token. You can see full instructions on the GitHub page . In short, once logged in to GitHub, click your profile icon in the top right corner and select Settings. From the options which appear on the left of the screen, select Developer settings. Next select Personal access tokens followed by clicking the Generate new token button. As the note, you can use sveltekit-graphql-github. For this project you will only need the public_repo permission under repo. Finally scroll down to the bottom of the screen and select Generate token. Make a note of the token which the console displays, you will need this shortly.

Now we have a GitHub personal access token. Why don't we create our SvelteKit project?

🗳️ Poll

Which Svelte framework are you most familiar with?
Voting reveals latest results.

🧱 Building our SvelteKit App to Query the GitHub API

If you were creating a blog site, you would start with the SvelteKit Blog Starter. However we are just building a simple (literally) single page app, so we will start from scratch. You might find this useful if this is your very first SvelteKit project (if it is your first, also take a look at the guide on Getting Started with SvelteKit). We start by spinning up a skeleton site. If you prefer yarn or npm, swap out the pnpm command:

pnpm init [email protected] sveltekit-graphql-github && cd $_
pnpm install
pnpm run dev

The app should be up and running now on your machine at http://localhost:3000 . If something else is already running on port 3000, don't worry, we'll see how to change ports in a moment. We need a few packages for this project, let's install them all at once:

pnpm i -D @apollo/client @fontsource/fira-sans @fontsource/merriweather
@sveltejs/[email protected] dayjs env-cmd graphql node-fetch sass
svelte-preprocess

What do we have here? @apollo/client, graphql and node-fetch will be used to make GraphQL queries. We will use @fontsource/fira-sans, @fontsource/merriweather, dayjs, sass and svelte-preprocess for styling and formatting. @sveltejs/[email protected] builds a static SvelteKit site. env-cmd is a handy utility for keeping our secrets secret. Speaking of which, next we will add some environment variables to the app.

Environment Variables

Our app will have a client part and a server part. We will build a static site, which means (in production) the server code only runs once when the static site is being generated. Only the server needs to know our secrets for this project, so we do not prefix them with VITE_ and we use env-cmd to access them. There is a little more explanation of environment variables in the Getting Started with SvelteKit post. Anyway, create a .env file in the project's root folder and paste in GitHub personal access token from the previous section:

.env
shell
GRAPHQL_ENDPOINT="https://api.github.com/graphql"
GITHUB_PERSONAL_ACCESS_TOKEN="PASTE_YOUR_TOKEN_IN_HERE"

The GraphQL endpoint is not really secret in this case, but if you were querying another API which was private, you would definitely not want to add it to you committed repo code. To be able to access the environment variables, we need to modify our npm scripts in package.json:

package.json
json
1{
2 "name": "sveltekit-graphql-github",
3 "version": "0.0.1",
4 "scripts": {
5 "dev": "env-cmd svelte-kit dev -p 3000",
6 "build": "env-cmd svelte-kit build",
7 "preview": "svelte-kit preview -p 3000",
8 "lint": "prettier --check --plugin-search-dir=. . && eslint --ignore-path .gitignore .",
9 "format": "prettier --write --plugin-search-dir=. ."
10 },

Also change the ports in lines 5 and 7 if you need to. Next, we will set up the backend and then add the front end afterwards and finally style it.

Apollo Client Set Up

This Apollo Client code is based on a Stack Overflow answer . As the solution suggests, we will only import the parts of Apollo Client which we need. Make a src/lib/utilities folder in your project and add an apolloClient.js file with this code:

src/lib/utilities/apolloClient.js
javascript
1import fetch from 'node-fetch';
2import { ApolloClient } from '@apollo/client/core/core.cjs.js';
3import { HttpLink } from '@apollo/client/link/http/http.cjs.js';
4import { InMemoryCache } from '@apollo/client/cache/cache.cjs.js';
5import { setContext } from '@apollo/client/link/context/context.cjs.js';
6
7class Client {
8 constructor() {
9 if (Client._instance) {
10 }
11 Client._instance = this;
12
13 this.client = this.setupClient();
14 }
15
16 setupClient() {
17 const link = new HttpLink({
18 uri: process.env['GRAPHQL_ENDPOINT'],
19 fetch
20 });
21 const authLink = setContext((_, { headers }) => {
22 return {
23 headers: {
24 ...headers,
25 authorization: `Bearer ${process.env['GITHUB_PERSONAL_ACCESS_TOKEN']}`
26 }
27 };
28 });
29 const client = new ApolloClient({
30 credentials: 'include',
31 link: authLink.concat(link),
32 cache: new InMemoryCache()
33 });
34 return client;
35 }
36}

We have modified the code from the Stack Overflow question to authorise us on the GitHub API. If you use this code on another project using an API which does not ned authorisation, remove lines 2128 and also change line 31 to read link,.

Query Endpoint

We will configure our app so the user's browser queries an endpoint on our app's server. That endpoint will respond with the GitHub data the client needs to render. This is not quite how things happen in our case as are generating a static app, but this explanation should give a clearer picture of what we are doing here. SvelteKit uses slug-based routing. The client will send a POST request to the endpoint /query/repositories.json, so we need to create a file at src/routes/query/repositories.json.js to answer that request. Create a file at that location and paste this code into it:

src/lib/utilities/apolloClient.js
javascript
1import { client } from '$lib/utilities/apolloClient.js';
2import { gql } from '@apollo/client/core/core.cjs.js';
3
4export async function post(request) {
5 try {
6 const { limit } = request.body;
7 const query = gql`
8 query RepositoriesQuery($limit: Int) {
9 viewer {
10 login
11 name
12 repositories(first: $limit, orderBy: { field: STARGAZERS, direction: DESC }) {
13 nodes {
14 id
15 createdAt
16 name
17 description
18 resourcePath
19 pushedAt
20 stargazerCount
21 }
22 }
23 }
24 }
25 `;
26 const { data } = await client.query({
27 query,
28 variables: { limit }
29 });
30 return {
31 body: JSON.stringify({ data })
32 };
33 } catch (err) {
34 console.error('Error: ', err);
35 return {
36 status: 500,
37 error: 'Error receiving data'
38 };
39 }
40}

We only need to respond to POST requests so our file at this endpoint only contains a post function,

  • in line 6 we destructure the limit variable which we will pass in a JSON post from the client. This is the number of posts we want to receive,

  • lines 725 contain the actual query, notice we use the limit variable to supply the first parameter in our query (line 12). You can go town here and add other parameters you want to query for, like repo code languages and tags,

  • lines 2629 is where we use Apollo Client to make the query. If you used hooks with Apollo Client in React, it might be some time since you have last seen this syntax! We don't need mutations here, but if you do need a mutation in one of your projects, the equivalent code would look like this:

const { data } = await client.mutate({
mutation,
variables: { limit }
});

You would need to define your mutation GraphQL in a similar way to the query we have above.

  • finally in lines 3032, we convert the data to a JSON string and respond to the request.

We go client side next!

Browser Client Page

We only have a single page for this app. First replace the svelte code in src/routes/index.svelte with this, then we will take a closer look:

src/lib/utilities/apolloClient.js
svelte
1<script context="module">
2 export const prerender = true;
3 export async function load({ fetch }) {
4 const url = '/query/repositories.json';
5 const res = await fetch(url, {
6 method: 'POST',
7 credentials: 'same-origin',
8 headers: {
9 'Content-Type': 'application/json'
10 },
11 body: JSON.stringify({
12 limit: 5
13 })
14 });
15 const { data } = await res.json();
16 if (res.ok) {
17 return {
18 props: { data }
19 };
20 }
21
22 return {
23 status: res.status,
24 error: new Error(`Couldn't load ${url}`)
25 };
26 }
27</script>
28
29<script>
30 import dayjs from 'dayjs';
31 import relativeTime from 'dayjs/plugin/relativeTime.js';
32 export let data;
33
34 dayjs.extend(relativeTime);
35
36 const { login: user, repositories: repoNodes } = data.viewer;
37 const { nodes: repos } = repoNodes;
38 const repoCount = repos.length;
39
40 const fromNow = (date) => {
41 const daysJSDate = dayjs(date);
42 return daysJSDate.fromNow();
43 };
44</script>
45
46<div class="container">
47 <div class="content">
48 <h1 class="heading">{`${user}'s GitHub`}</h1>
49
50 {#if repoCount > 0}
51 {#each repos as repo, index}
52 <article aria-posinset={index + 1} aria-setsize={repoCount} class="repo">
53 <h2>
54 {repo.name}
55 </h2>
56 <span>
57 <span class="meta">Updated {fromNow(repo.pushedAt)}</span>
58 {#if repo.stargazerCount > 0}<span class="meta stars">🌟 {repo.stargazerCount}</span>{/if}
59 </span>
60 {#if repo.description != null}
61 <p><a href={`https://github.com/${repo.resourcePath}`}>{repo.description}</a></p>
62 {/if}
63 </article>
64 {/each}
65 {:else}
66 <p>No repos found :/</p>
67 {/if}
68 </div>
69</div>

If this is the first svelte code you're looking at, you can see it looks like a kind of a superset of HTML.

The code has three blocks. We will add a fourth block for styling in a moment. The first block is a Javascript module. It contains our load function. For SvelteKit the loader runs before the page renders. Here it is used to get the data from the server endpoint we just created. The page should render in your browser (albeit unstyled). Do you see a list of your public repos? Try changing the limit in line 12 from 5 to 1 and saving. As long as you have more than one public repo in your GitHub, you should see we pull back less data in the GraphQL query and only that data is rendered.

Prerendering

Going back to line 2, this doesn't have an impact when we are running in dev mode. When we build the site though, the prerender instruction tells SvelteKit to generate a static site. This means we pull all the data during the build process and never update it. If we add new repos and want them to appear on our page, we just have to rebuild it. Prerendering can generally be used where the same data is presented to every site visitor. The prerendered page should load quicker since we do not need to query for data while the page is loading up, it will already be encoded in the site's HTML. For the prerendered site, the load function only runs during build.

In lines 1719 you see we return a data prop. This is available in the next script block, which runs when the page renders. In line 32 (next block) you see the way we import a prop is by using the export let syntax. See the Svelte tutorial for more on props . This is confusing initially, though you will soon get used to it. The rest of the block is everyday Javascript you would see in other frameworks.

Rendered Code

The rendered content is in the third block. You can see a few Svelte features here:

  • line 50 opens an if block. This is how we can do conditional rendering in Svelte . We render the code if lines 5164 if there are some repos in the response. Otherwise we render the paragraph in line 67.

  • lines 5164 show how to loop. Looking at line 51, the repos variable refers to an array which is defined in the previous script block. The repo and index variables are temporary loop variables and used to get data from each element as we loop over the array (think something line {repos.map((repo, index)) => <>{renderMe}</>)} if you are used to React).

The remaining code has further examples of conditional rendering and accessing Javascript variables.

Let's add some Sass

I love to use Sass for styling, though you can use tailwind or other tools with SvelteKit. There are a couple of things we need to do to set up Sass. First we will configure SvelteKit to use the preprocessor. Edit sveltekit.config.js:

1/** @type {import('@sveltejs/kit').Config} */
2import adapter from '@sveltejs/adapter-static';
3import preprocess from 'svelte-preprocess';
4
5const config = {
6 preprocess: [
7 preprocess({
8 scss: {
9 prependData: "@import 'src/lib/styles/variables.scss';"
10 }
11 })
12 ],
13 kit: {
14 adapter: adapter(),
15 // hydrate the <div id="svelte"> element in src/app.html
16 target: '#svelte'
17 }
18};

Before we look at styling, we also have some code here which tells SvelteKit to generate a static site. You can deploy this site to Cloudflare Pages , Netlify, Render or other providers. We just need to import the static adapter in line 2 and use it in line 14.

Here as well as setting up the preprocessor, in line 9 we make some variables available. To start create this file at src/lib/styles/variables.scss, then paste in the code from variables.scss in the GitHub repo . Now create index.sccs , normalise.css and styles.scss in the same folder and follow the links to find the code you need to paste in.

We will need to import those styles so they are available for our page. On a larger site you would create a layout component and import this data there to make it available to every page on the site. Even though we have a single page on our site, we will do the same, so you can see how it's done. Create a default layout file at src/routes/__layout.svelte:

1<script>
2 import '$lib/styles/normalise.css';
3 import '$lib/styles/index.scss';
4 import '@fontsource/merriweather/400.css';
5 import '@fontsource/merriweather/700.css';
6 import '@fontsource/fira-sans/400.css';
7</script>
8
9<slot />

Here we import our the fonts we want to self host (we installed them earlier) as well as the styles. This is a layout file and the <slot /> element in line 9 is a placeholder for our content. If you are using Svelte for the first time, add a <h1> element above it and a paragraph below so you can really see it's a layout template. On a larger site, we would add any headers and footers which appear on every page to this file.

Finally, to complete style, paste these style at the bottom of src/routes/index.svelte

src/routes/index.svelte
svelte
71<style lang="scss">
72 .container {
73 background: $color-theme-4;
74 border: solid $color-theme-3 $spacing-px;
75 border-radius: $spacing-1;
76 margin: 0;
77 width: 70%;
78 margin: $spacing-12 auto;
79 padding: $spacing-2 $spacing-4;
80
81 p {
82 font-size: $font-size-2;
83 margin-top: $spacing-8;
84 }
85 }
86 .heading {
87 color: $color-theme-3;
88 }
89
90 .content {
91 margin: $spacing-12;
92 color: $color-theme-3;
93 }
94
95 .repo {
96 border: solid $color-theme-3 $spacing-px;
97 border-radius: $spacing-1;
98 background-color: $color-theme-5;
99 margin: $spacing-6 $spacing-0;
100 padding: $spacing-4;
101 color: $color-theme-3;
102
103 h2 {
104 margin-top: $spacing-0;
105 margin-bottom: $spacing-4;
106 color: $color-theme-3;
107 font-size: $font-size-4;
108 }
109
110 .stars {
111 font-weight: $font-weight-bold;
112 }
113 }
114
115 .repo:hover {
116 background-color: $color-theme-3;
117 color: $color-theme-5;
118
119 h2 {
120 color: $color-theme-5;
121 }
122
123 a {
124 color: $color-theme-4;
125 }
126
127 .meta {
128 border: solid $color-theme-4 $spacing-px;
129 padding: #{$spacing-1 - $spacing-px} #{$spacing-2 - $spacing-px};
130 }
131 }
132
133 .meta {
134 font-size: $font-size-1;
135 background-color: $color-theme-3;
136 color: $color-theme-4;
137 padding: $spacing-1 $spacing-2;
138 border-radius: $spacing-1;
139 }
140
141 @media screen and (max-width: $desktop-breakpoint) {
142 .container {
143 width: 95%;
144 }
145 .content {
146 margin: $spacing-12 $spacing-2;
147 }
148 .repo {
149 margin: $spacing-10 $spacing-0;
150 }
151 }
152</style>

We tell SvelteKit our styles are using scss in line 71 and then have access to the variable defined in the global styles we created a moment ago.

🔥 How Does in Look?

Use Apollo Client with SvelteKit: Final Result

Normally at this stage in our tutorials, we run some tests. I think all you need to do is refresh your browser and you should see your repos nicely styled. Let me know if something is not working, or if I haven't explained some part well. That way I can update the tutorial for anyone else following later.

🙌🏽 Use Apollo Client with SvelteKit: Wrapup

That's it for this post. We have seen:

  • how to build a SvelteKit site from scratch,
  • that GraphQL offers a convenient way to access GitHub meta,
  • how to use Apollo Client with SvelteKit to query a GraphQL API.

As always suggestions for improvements, together with requests for explanations and feedback are more than welcome. Also let me know what other features you would like implemented on the starter. The full code for this tutorial on how to use Apollo Client with SvelteKit is on the Rodney Lab GitHub repo . There is also a live demo site running on Render .

🙏🏽 Use Apollo Client with SvelteKit: Feedback

Have you found the post useful? 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 couple of dollars, rupees, 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.