Build with SvelteKit and GraphQL

Rate this content
Bookmark

Have you ever thought about building something that doesn't require a lot of boilerplate with a tiny bundle size? In this workshop, Scott Spence will go from hello world to covering routing and using endpoints in SvelteKit. You'll set up a backend GraphQL API then use GraphQL queries with SvelteKit to display the GraphQL API data. You'll build a fast secure project that uses SvelteKit's features, then deploy it as a fully static site. This course is for the Svelte curious who haven't had extensive experience with SvelteKit and want a deeper understanding of how to use it in practical applications.

Table of contents:
- Kick-off and Svelte introduction
- Initialise frontend project
- Tour of the SvelteKit skeleton project
- Configure backend project
- Query Data with GraphQL
- Fetching data to the frontend with GraphQL
- Styling
- Svelte directives
- Routing in SvelteKit
- Endpoints in SvelteKit
- Deploying to Netlify
- Navigation
- Mutations in GraphCMS
- Sending GraphQL Mutations via SvelteKit
- Q&A

This workshop has been presented at GraphQL Galaxy 2021, check out the latest edition of this Tech Conference.

FAQ

GraphCMS is a headless content management system (CMS) that uses GraphQL to deliver content to users. It was one of the first GraphQL-based CMSs and provides modern web development best practices out of the box.

Svelte is a compiler framework that allows developers to break up their projects into components, similar to Vue and Angular. Unlike Vue, Svelte does not use a virtual DOM. Instead, it compiles HTML, CSS, and JavaScript in the build step, delivering plain old HTML, CSS, and JavaScript to the browser.

SvelteKit is a framework for building Svelte projects. It offers modern web development best practices, such as code splitting and file-based routing, out of the box. It is still in public beta, but once it reaches version 1, it will be the standard way to build projects in Svelte.

To query data with GraphQL in a SvelteKit project, you can use the GraphQL request library. Define a GraphQL client and create a query. You can then fetch the data in the load function of your SvelteKit component, returning the data as props to be used in your component.

In SvelteKit, routes are created by adding files and folders in the 'routes' directory. For example, creating a file named 'posts/[slug].svelte' will create a dynamic route that can be accessed via 'posts/{slug}'. The 'slug' parameter can then be used to fetch specific data for that route.

Endpoints in SvelteKit can be created by adding files with the '.json.js' extension in the 'routes' directory. You can define HTTP methods like GET, POST, etc., and return data as JSON. These endpoints can be fetched from within your SvelteKit components to get server-side data.

The load function in SvelteKit is used to fetch data before the component mounts. It runs on both the server and the client, allowing you to fetch data from APIs, databases, or other sources and return it as props to be used in your SvelteKit components.

In SvelteKit, environment variables can be defined in a '.env' file. The variables should be prefixed with 'VITE_' to be accessible in your project. You can then use these variables in your SvelteKit components or endpoints by importing them using 'import.meta.env'.

To deploy a SvelteKit project to Vercel, you can use the Vercel CLI. Run 'npx vercel' in your project directory to set up and deploy your project. Ensure that your environment variables are configured in the Vercel dashboard under 'Environment Variables'. Each push to your connected Git repository will trigger a new deployment.

Tailwind CSS provides utility-first CSS classes that make it easy to style your components without writing custom CSS. It can be configured in a SvelteKit project using 'svelte-add'. Plugins like DaisyUI and Tailwind CSS Typography can further enhance your styling capabilities, making your project more presentable with minimal effort.

Scott Spence
Scott Spence
140 min
08 Dec, 2021

Comments

Sign in or register to post your comment.

Video Summary and Transcription

This workshop focuses on using Svelte and SvelteKit to build a GraphQL-based CMS. It covers project setup, configuration, and working with GraphCMS. The workshop also explores fetching data from endpoints, styling with SvelteAdd, and working with blog post data and routing. Troubleshooting Tailwind CSS configuration and deployment with Versel are also discussed.
Available in Español: Construir con SvelteKit y GraphQL

1. Introduction to Svelte and Agenda

Short description:

Hi, my name's Scott. We are one of the first GraphQL based CMSs. We're all in on GraphQL. Let's take a quick look at the agenda. We'll create a front end and a back end. We'll query data with GraphQL. We'll display data in our Svelte project. We'll manage data with Svelte directives. We'll look at rooting in Svelte and endpoints. We'll cover deploying to production. Svelte is a compiler framework that builds HTML, CSS, and JavaScript. SvelteKit is the one-stop shop for building projects in Svelte.

Hi, my name's Scott. I'm a Developer Advocate over at GraphCMS. We are one of the, if not the, only, sorry, the first, sort of, GraphQL based CMSs out there. We're all in on GraphQL and that's pretty much how we deliver our content for our users.

So, let's take a quick look at the agenda. And I know I've not updated the date on these slides. It's showing as So, we're going to create a front end and a back end. We're going to look at some querying data with GraphQL. We're going to take a look at displaying that data in our Svelte project. We'll take a quick look at Svelte directives for managing data on the Svelte file, once it's coming to the component. We'll be looking at rooting in Svelte, along with endpoints. And we'll take a look at deploying to production, if we have enough time.

Okay. So, what is Svelte? So, it's a compiler framework which allows you to break up your projects into two components, much like Vue and Angular. What is different with Svelte as opposed to Vue is there's no virtual DOM. Svelte builds HTML CSS and JavaScript in the build step, so what the browser gets is just plain old HTML, CSS and JavaScript, nice and easy to manage. Svelte isn't particularly new, V1 was released in late 2016, around November I think. So what I'm going to be concentrating on is SvelteKit. It is going to be the one stop shop for building any of your projects in Svelte.

2. SvelteKit and Project Setup

Short description:

At the moment, if you're going to create a new project with SvelteKit, it's still in public beta. SvelteKit provides modern web development best practices out of the box, including code splitting and routing. Svelte is like React for vegans, offering HTTP endpoints and file-based routing. Svelte also introduces Visvelte, a superset of HTML, which allows for reactivity within components. The each directive is used for looping around objects. Let's move on to the front end and initialize a Svelte project using the terminal. We'll be using Versell as the deployment target. The project includes a README, package.json, and JS config file for defining paths. We'll also configure the prettier file.

So at the moment if you're going create a new project with SvelteKit, at next, Svelte at next and give it a project name. Once it goes to V1 because SvelteKit is still in public beta, once it goes to V1, at next it will fall away and how anyone builds a project in Svelte. So there's modern web development best practices out of the box with SvelteKit. It's got code splitting built in and fire routing and all the niceness as, you know, we as front end developers are accustomed to.

So Svet is React for vegans. Love it. You get HTTP end points. We're going to go into detail on them. So you have HTM points, you get your get, what HTM points, get, put, delete. But it's not delete, because delete is a reserve word in JavaScript, so it's just DEL. So you can manage stuff that way, which is great. I've already covered file based routing. And it's very similar to NextJS or Next. But you use this instead of React or Vue. Okay. I don't think I sent out the resources for this. So I'm going to gloss over this and skip over to the next slide here.

So Visvelte, which I didn't cover, it's a super set of HTML. So this would look very familiar if you're coming from a sort of an HTML CSS and JavaScript background, where we can define things in some script tags here. We can define our count variable and then increment it and decrement it with sorry, just increment it here with the on click for our button here. And we have declarations. So this is how we get around state changes within a component. We use this dollar colon syntax here. If you're not familiar with it, I know it might look a bit funky, but this is like a JavaScript label. It's a valid JavaScript. But it's not used anywhere. So Rich Harris and the team have taken it on themselves to use this for reactivity within components. So we've got directives here, which is we've got an if block. We can use else as well. So we use the curly braces to define our directive and then we can start working with it within those. We're going to come to using those in our project very soon. So, yeah, this is going to be like the meat and potatoes for the each directive, which you just use for looping around blocks of like for looping around objects. So let's get started. I think these are just toilet slides now. Let's just go to the front end. I'm going to need a terminal. So everyone okay with, let's just bump up this font size here. So let's see. Everyone see the screen okay? Thumbs up from Robert, thank you. Um, okay. So, let's go into my example projects here. And I'm just going to NPM init Svelte next and what I'm going to do here, we're going to say computation.v1. Zip code for 20. 21, let's see, this is going to create our Svelte projects inside a folder defined as GraphQL Galaxy Workshop 2021 so let's hit enter here. And first I'm just going to say skeleton projects. We're not going to use TypeScript or ES Lint. If I go into the workshop folder now, change into here, it just changed my view. If anyone's got any issues just shoot out, possibly at me in the Discord so in this channel here. Move this over to the side. Let's just switch back on here. Right, let's take a quick look at this project here. So if I go into VS Code, my code editor. Right, so we've got our Svelte config. So this is a new addition to the Svelte Kit starter. This is Adapto Auto. So in the past, I still need to look into this, but I know for the purposes of this I think this will be fine. With Svelte Kit, it doesn't really have any opinions on like deployment targets so there's several available. Let's see if we can get one up here. And again, if there's any issues to shout, I'm just going to try my biggest possible here. And here we go, Adapters. So I'm not sure if these have been updated since the inception of this adaptor also here, but we've got build environments for Netlify, Versell, and Cloudflare, and of course you can build your own adapter if none of those fit. For the purposes of this workshop, I think I'll just be using Versell, and if there's anything specific you need to know about any other ones, if you're just going to be doing a pure static build, there's some gotchas around that as well, so just shout if there's anything you need information on with regards to that. Anyway, moving on, we've got our README, we've got our package.json here, everything is installed as a dev dependency. There's no run time. I'm talking, I'm actually looking at my camera, and I realise there's no camera on, so I'll stop doing that. So we've got a JS config file here. This is so we can define like our short paths for our lib, we can also put in components, anything else you want to define this will give us a little bit of syntactic sugar for importing files into our projects. We've got a prettier file here. I'm just going to replace this with my own configuration. I'm going to need to install as well.

Watch more workshops on topic

Developing Dynamic Blogs with SvelteKit & Storyblok: A Hands-on Workshop
JSNation 2023JSNation 2023
174 min
Developing Dynamic Blogs with SvelteKit & Storyblok: A Hands-on Workshop
Top Content
Featured WorkshopFree
Alba Silvente Fuentes
Roberto Butti
2 authors
This SvelteKit workshop explores the integration of 3rd party services, such as Storyblok, in a SvelteKit project. Participants will learn how to create a SvelteKit project, leverage Svelte components, and connect to external APIs. The workshop covers important concepts including SSR, CSR, static site generation, and deploying the application using adapters. By the end of the workshop, attendees will have a solid understanding of building SvelteKit applications with API integrations and be prepared for deployment.
Build Modern Applications Using GraphQL and Javascript
Node Congress 2024Node Congress 2024
152 min
Build Modern Applications Using GraphQL and Javascript
Featured Workshop
Emanuel Scirlet
Miguel Henriques
2 authors
Come and learn how you can supercharge your modern and secure applications using GraphQL and Javascript. In this workshop we will build a GraphQL API and we will demonstrate the benefits of the query language for APIs and what use cases that are fit for it. Basic Javascript knowledge required.
End-To-End Type Safety with React, GraphQL & Prisma
React Advanced Conference 2022React Advanced Conference 2022
95 min
End-To-End Type Safety with React, GraphQL & Prisma
Featured WorkshopFree
Sabin Adams
Sabin Adams
In this workshop, you will get a first-hand look at what end-to-end type safety is and why it is important. To accomplish this, you’ll be building a GraphQL API using modern, relevant tools which will be consumed by a React client.
Prerequisites: - Node.js installed on your machine (12.2.X / 14.X)- It is recommended (but not required) to use VS Code for the practical tasks- An IDE installed (VSCode recommended)- (Good to have)*A basic understanding of Node.js, React, and TypeScript
GraphQL for React Developers
GraphQL Galaxy 2022GraphQL Galaxy 2022
112 min
GraphQL for React Developers
Featured Workshop
Roy Derks
Roy Derks
There are many advantages to using GraphQL as a datasource for frontend development, compared to REST APIs. We developers in example need to write a lot of imperative code to retrieve data to display in our applications and handle state. With GraphQL you cannot only decrease the amount of code needed around data fetching and state-management you'll also get increased flexibility, better performance and most of all an improved developer experience. In this workshop you'll learn how GraphQL can improve your work as a frontend developer and how to handle GraphQL in your frontend React application.
Build a Headless WordPress App with Next.js and WPGraphQL
React Summit 2022React Summit 2022
173 min
Build a Headless WordPress App with Next.js and WPGraphQL
Top Content
WorkshopFree
Kellen Mace
Kellen Mace
In this workshop, you’ll learn how to build a Next.js app that uses Apollo Client to fetch data from a headless WordPress backend and use it to render the pages of your app. You’ll learn when you should consider a headless WordPress architecture, how to turn a WordPress backend into a GraphQL server, how to compose queries using the GraphiQL IDE, how to colocate GraphQL fragments with your components, and more.
Relational Database Modeling for GraphQL
GraphQL Galaxy 2020GraphQL Galaxy 2020
106 min
Relational Database Modeling for GraphQL
Top Content
WorkshopFree
Adron Hall
Adron Hall
In this workshop we'll dig deeper into data modeling. We'll start with a discussion about various database types and how they map to GraphQL. Once that groundwork is laid out, the focus will shift to specific types of databases and how to build data models that work best for GraphQL within various scenarios.
Table of contentsPart 1 - Hour 1      a. Relational Database Data Modeling      b. Comparing Relational and NoSQL Databases      c. GraphQL with the Database in mindPart 2 - Hour 2      a. Designing Relational Data Models      b. Relationship, Building MultijoinsTables      c. GraphQL & Relational Data Modeling Query Complexities
Prerequisites      a. Data modeling tool. The trainer will be using dbdiagram      b. Postgres, albeit no need to install this locally, as I'll be using a Postgres Dicker image, from Docker Hub for all examples      c. Hasura

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Full Stack Documentation
JSNation 2022JSNation 2022
28 min
Full Stack Documentation
Top Content
The Talk discusses the shift to full-stack frameworks and the challenges of full-stack documentation. It highlights the power of interactive tutorials and the importance of user testing in software development. The Talk also introduces learn.svelte.dev, a platform for learning full-stack tools, and discusses the roadmap for SvelteKit and its documentation.
From GraphQL Zero to GraphQL Hero with RedwoodJS
GraphQL Galaxy 2021GraphQL Galaxy 2021
32 min
From GraphQL Zero to GraphQL Hero with RedwoodJS
Top Content
Tom Pressenwurter introduces Redwood.js, a full stack app framework for building GraphQL APIs easily and maintainably. He demonstrates a Redwood.js application with a React-based front end and a Node.js API. Redwood.js offers a simplified folder structure and schema for organizing the application. It provides easy data manipulation and CRUD operations through GraphQL functions. Redwood.js allows for easy implementation of new queries and directives, including authentication and limiting access to data. It is a stable and production-ready framework that integrates well with other front-end technologies.
Local State and Server Cache: Finding a Balance
Vue.js London Live 2021Vue.js London Live 2021
24 min
Local State and Server Cache: Finding a Balance
Top Content
This Talk discusses handling local state in software development, particularly when dealing with asynchronous behavior and API requests. It explores the challenges of managing global state and the need for actions when handling server data. The Talk also highlights the issue of fetching data not in Vuex and the challenges of keeping data up-to-date in Vuex. It mentions alternative tools like Apollo Client and React Query for handling local state. The Talk concludes with a discussion on GitLab going public and the celebration that followed.
The Wind and the Waves: The formation of Framework Waves from the Epicenter
JSNation 2022JSNation 2022
19 min
The Wind and the Waves: The formation of Framework Waves from the Epicenter
Top Content
Our understanding of innovation is wrong. Innovations are not introduced by a single point of light. The story of who invented the computer is not linear. Many steps forward led to the development of the computer. Angular has shaped and influenced multiple JavaScript waves, and Angular v14 simplifies development with standalone components.
Batteries Included Reimagined - The Revival of GraphQL Yoga
GraphQL Galaxy 2021GraphQL Galaxy 2021
33 min
Batteries Included Reimagined - The Revival of GraphQL Yoga
Envelope is a powerful GraphQL plugin system that simplifies server development and allows for powerful plugin integration. It provides conformity for large corporations with multiple GraphQL servers and can be used with various frameworks. Envelope acts as the Babel of GraphQL, allowing the use of non-spec features. The Guild offers GraphQL Hive, a service similar to Apollo Studio, and encourages collaboration with other frameworks and languages.
Rock Solid React and GraphQL Apps for People in a Hurry
GraphQL Galaxy 2022GraphQL Galaxy 2022
29 min
Rock Solid React and GraphQL Apps for People in a Hurry
The Talk discusses the challenges and advancements in using GraphQL and React together. It introduces RedwoodJS, a framework that simplifies frontend-backend integration and provides features like code generation, scaffolding, and authentication. The Talk demonstrates how to set up a Redwood project, generate layouts and models, and perform CRUD operations. Redwood automates many GraphQL parts and provides an easy way for developers to get started with GraphQL. It also highlights the benefits of Redwood and suggests checking out RedwoodJS.com for more information.