FOR DEVELOPERS

How to Implement Routing in Svelte Web App

How to Implement Routing in Svelte Web App

In 2016, a new framework for building UIs entered the space dominated by others like React and Vue: Svelte. One of its distinctive features is that it maintains the syntactical sugar of basic JavaScript. It has taken a pre-existing syntax from JavaScript and used it to its advantage.

The work done by React and Vue during runtime to build and interact with the interface sees Svelte doing it as a build step. This reduces the effort of performing complicated calculations every time something changes on the UI.

In this article, we’ll take a detailed look at Svelte routing and explore some of the framework’s features.

Basic features of Svelte

Industry surveys show that Svelte has been voted among the most loved web frameworks. It provides an interactive tutorial/playground to get started with a few notable features built-in, such as:

  • Easings and time-based transitions.
  • Ease of reactivity as simple as a variable declaration.
  • Scoped CSS for specific components/pages.
  • The provision of svelte-kit, a packaged solution like create-react-app to get started with development.

Developing a sample app using Svelte

Let’s jump right into the development of a sample app with Svelte, assuming you’re already on the latest version of node.

Running

npm create svelte@latest routing-app

It asks the following questions to customize your project.

Routing with svelte.webp

After the setup is done, the folder structure is presented with the basic things required to start development.

Svelte uses Vite for tooling, which is considerably faster than most of the bundlers/tools out there.

A few specific files to be noted here are:

  • App.html within the src folder, which is the entry or main file where HTML will get rendered.
  • A folder called routes that we’ll discuss more on later.
  • The app.d.ts file to define the types for the entire app based on page data, platforms, errors and locals. You can find more about it here: "https://kit.svelte.dev/docs/types#app"
  • A static folder for adding images or other external scripts based on your needs, and a test folder where you can add your unit test cases.
  • Config files of the relative tools based on the customizations you select while setting up the app, such as for ESLint, jsconfig, Prettier, playwright, Svelte, and Vite.

Let's install the node_modules which install the required packages from the package.json file in order to use the Yarn command.

We will focus on the scripts object in the package.json file. We will use the dev script for development.

As soon as you run yarn dev, Vite starts a development server running on port 5173 that presents a simple welcome web page and a link to its documentation.

javascript routing library.webp

You’ll find a +page.svelte file under routes from where it is being routed to. You can edit anything inside the page to see it being updated in real-time.

Now, let’s see how JavaScript works in Svelte.

Update the contents of the file as below.

<script>
  let welcomeMessage = 'Welcome to Svelte'
</script>
<h1>{welcomeMessage}</h1>
<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>

You can see the message getting embedded and rendered on the page. Now, let’s add some dynamic JavaScript to update the same.

Once you update the logic below, it adds a button that increases the time count and views upon clicking.

<script>
  let welcomeMessage = 'Welcome to Svelte'
  let time = 0
</script>
<h1>{welcomeMessage}</h1>
<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>
<p>You've Clicked {time} time{time > 1 ? 's' : ''}</p>
<button on:click={() => time++} >Click here.</button>

Let’s see how we can add components and props.

Under the src directory, create a folder ‘components’. Within that, create a file MessageContainer.svelte with the following contents.

Here, we exported a variable message that will be sent as props from the parent component. This, in turn, will be embedded under the p tag.

<script>
  // src/components/MessageContainer.svelte
  export let message = '';
</script>
<p>{message}</p>

Let’s import the component into the page, +page.svelte, and pass the props. It will look like something below upon being updated.

<script>
  import MessageContainer from "../components/MessageContainer.svelte";
  let welcomeMessage = 'Welcome to Svelte'
  let time = 0
</script>
<h1>{welcomeMessage}</h1>
<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>
<MessageContainer message={`You've Clicked ${time} time${time > 1 ? 's' : ''}`} />
<button on:click={() => time++} >Click here.</button>

As seen, we are importing a component and rendering it at the place where the previous message was and passing the message as a prop with the values that are updated.

Exploring Svelte routing

Now that we know the basics of Svelte, let’s move on to routing.

Navigating is done using different approaches based on the requirements of the application. Here, we will focus on a simple case of Svelte routing using a file.

Creating a folder under routes and adding +page.svelte file to it adds a route to your web application.

In your project, add a sample folder as a bio and a simple page.

svelte ssr.webp

Once you create this with the content added, try to access the route from your browser. You’ll be presented with this:

svelte router.webp

You can also use a slot to render multiple sub-pages within the current page to navigate. For this to work, you need to add a file, +layout.svelte, under bio.

You can create four different folders within the bio: front-end, back-end, mobile and freelance, with some content inside +page.svelte under each of these folders.

Now, link all of these pages in layout.svelte. It will look like what’s below:

<nav>
  <a href="/bio">My Bio</a>
  <a href="/bio/front-end">Front-end</a>
  <a href="/bio/back-end">Back-end</a>
  <a href="/bio/mobile">Mobile</a>
  <a href="/bio/freelance">Freelance</a>
</nav>
<slot></slot>

The slot is the section where your sub-page gets rendered. It will look something like this:

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/58a465b0-cea4-4f72-a9d1-
f7a42a1944c6/Screen_Recording_2023-02-06_at_9.13.42_PM.mov

Let’s say you want to customize the name dynamically from query parameters, which is "http://127.0.0.1:5173/bio?firstname=afroze&lastname=khan."

To access this, you can use the window.location.search using URLSearchParams class. On updating, the content will look like the following:

<script>
  import { onMount } from 'svelte'
  let firstName = '', lastName = '';
  onMount(() => {
    const params = new URLSearchParams(window.location.search);
    firstName = params.get('firstName') || 'John';
    lastName = params.get('lastName') || 'Doe';
  })
</script>

<h1> Hi, I'm {firstName} {lastName} </h1> <p>I'm a fullstack developer</p>

Now, you can update the firstName and lastName params and see your name getting rendered on the page. Here, you will use onMount from the Svelte package, which is like a callback function that gets called when the component is mounted.

Using this, assign it to firstName and lastName.

Svelte routing library.gif

These are some of the very basics of Svelte routing in SvelteKit, a back-end framework for Svelte. Now that you have the information you need, you can use it in future projects when building web applications.

Author

  • How to Implement Routing in Svelte Web App

    Afroze Kabeer Khan. M

    Author is a Full-stack developer and Polyglot programmer. He has experience in building an OTT platform and also has built a mobile application for a smart ring. He has worked with platforms like Web, Mobile, and Kiosk-based systems.

Frequently Asked Questions

This feature is not yet supported.

Yes, it supports TypeScript.

Svelte uses setContext and getContext. It also has a built-in store, "svelte/store", that manages global state.

You can find a repo named awesome-svelte on GitHub that has a great collection of these.

There is an official VS Code extension for Svelte.

Yes, svelte-routing or svelte-navigator. You can also use spa-router or abstract-state-router.

View more FAQs
Press

Press

What’s up with Turing? Get the latest news about us here.
Blog

Blog

Know more about remote work. Checkout our blog here.
Contact

Contact

Have any questions? We’d love to hear from you.

Hire remote developers

Tell us the skills you need and we'll find the best developer for you in days, not weeks.