What Is Svelte? A Beginner's Guide

Learn how Svelte works, explore Svelte 5 runes, build reusable components, and understand how SvelteKit helps you create complete web applications.

Beginner-friendly tutorial · Web Development · Svelte 5

Table of Contents

  1. What Is Svelte?
  2. Understanding Svelte 5
  3. Why Learn Svelte?
  4. Svelte vs Other Technologies
  5. Creating a Project
  6. Components and Reactivity
  7. Svelte 5 Runes
  8. Props and Events
  9. Forms and Binding
  10. Svelte Stores
  11. What Is SvelteKit?
  12. Routing and Dynamic Routes
  13. Loading Data and APIs
  14. Databases and Authentication
  15. TypeScript and CSS
  16. Accessibility and Performance
  17. Deployment
  18. Beginner Projects
  19. Common Mistakes
  20. Svelte Cheat Sheet
  21. Frequently Asked Questions

What Is Svelte?

Svelte is a modern framework for building web user interfaces and applications. It lets developers create interactive websites using components written with HTML, CSS, and JavaScript or TypeScript.

Unlike approaches that rely heavily on a runtime framework in the browser, Svelte uses a compiler to transform components into JavaScript during the build process.

Simple explanation: Svelte lets you write reusable interface components, and its compiler prepares them for use in a web application.

Svelte can be used for interactive buttons, forms, dashboards, product pages, blogs, and many other web interfaces.

What Is Svelte 5?

Svelte 5 introduced a modern reactivity system called runes. Runes are special syntax that help developers express how application state, derived values, effects, and component properties work.

Important Svelte 5 runes include:

  • $state — creates reactive state.
  • $derived — calculates values from other values.
  • $effect — runs side-effect logic when relevant state changes.
  • $props — declares component properties.

Svelte 5 also supports many older Svelte syntax patterns. When learning the current version, it is useful to understand the rune-based approach as well as older examples you may encounter.

Beginner tip: Learn one concept at a time. Start with $state, then move on to $derived, props, events, and effects.

Why Learn Svelte?

  • It provides a component-based way to build user interfaces.
  • HTML, CSS, and JavaScript can be organized in a single component file.
  • Svelte 5 provides an explicit approach to reactive state with runes.
  • The compiler can reduce the amount of framework work needed in the browser.
  • SvelteKit provides routing and application-level features.
  • It can be used for small websites and larger interactive applications.

Like every technology, Svelte has trade-offs. The best framework depends on the project, the team's experience, the required tools, and the hosting environment.

Svelte vs JavaScript

JavaScript is a programming language. Svelte is a framework and compiler system used to build user interfaces and applications.

Svelte uses JavaScript for application logic. You can also use TypeScript in Svelte projects.

Svelte vs React

Svelte React
Uses a compiler-based approach. Uses a library and its surrounding ecosystem.
Uses .svelte component files. Commonly uses JSX or TSX with JavaScript or TypeScript.
Svelte 5 provides runes for reactive state. Uses state, hooks, and other React APIs.
SvelteKit adds application framework features. Next.js is one popular framework built around React.

Svelte vs Vue

Svelte Vue
Uses a compiler-focused approach. Uses a framework with a reactive runtime.
Uses .svelte component files. Commonly uses .vue Single-File Components.
Svelte 5 uses runes for modern reactivity. Vue provides its own reactivity APIs.
SvelteKit provides application framework features. Nuxt is a popular framework in the Vue ecosystem.

Svelte vs Angular

Svelte Angular
Uses a compiler-focused component approach. Provides a broad, integrated application framework.
Components use Svelte syntax with HTML, CSS, and JavaScript or TypeScript. Components commonly use TypeScript, templates, and framework APIs.
SvelteKit provides additional application features. Angular includes many application-development tools in its ecosystem.

Creating a Svelte Project

A common way to create a new SvelteKit project is to use the Svelte CLI. You will need Node.js and npm installed on your development environment.

npx sv create my-svelte-app

Enter the project directory:

cd my-svelte-app

Install dependencies if they have not already been installed:

npm install

Start the development server:

npm run dev

The development tool will display a local address where you can preview the application in your browser.

Important: These commands require a command-line environment with Node.js and npm. You can read and edit Svelte code on a phone, but running the complete development toolchain may require an appropriate online development environment or another supported setup.

What Is a Svelte Component?

A Svelte component is commonly saved in a file ending in .svelte. A component can contain a script section, HTML-like markup, and a style section.

For example, a component named Greeting.svelte might look like this:

<script>
  let name = "TechLearn Hub";
</script>

<h1>Hello {name}!</h1>

<style>
  h1 {
    color: blue;
  }
</style>

The script defines data, the markup displays the greeting, and the style controls its appearance.

Why Use Components?

Components let you divide an application into smaller pieces. A website might have separate components for a navigation bar, footer, product card, login form, and user profile.

Reusable components can make a project easier to understand, update, test, and maintain.

Svelte 5 Runes

1. The $state Rune

The $state rune creates reactive state. When the value changes, Svelte updates the parts of the interface that depend on it.

<script>
  let count = $state(0);
</script>

<button onclick={() => count++}>
  Count: {count}
</button>

Each click increases the count by one, and the displayed number updates.

2. The $derived Rune

The $derived rune is useful when a value should be calculated from other reactive values.

<script>
  let price = $state(100);
  let quantity = $state(2);

  let total = $derived(price * quantity);
</script>

<p>Total: {total}</p>

Here, the total is calculated from the price and quantity. When either value changes, the derived value can update.

3. The $effect Rune

The $effect rune is designed for side effects that need to respond to changes in reactive state.

<script>
  let count = $state(0);

  $effect(() => {
    console.log("Count changed:", count);
  });
</script>

This example logs the count when the effect runs and its tracked dependencies change.

Remember: Effects are not the default way to calculate values. Use $derived for derived values and use $effect when an actual side effect is needed.

4. The $props Rune

Props allow a parent component to pass information to a child component. In Svelte 5, you can declare props using $props().

<script>
  let { name } = $props();
</script>

<h2>Hello {name}!</h2>

A parent component can pass a value to this component through its name property.

Conditional Rendering, Loops, and Events

Conditional Rendering

Svelte supports conditional blocks that display different content depending on a condition.

<script>
  let loggedIn = $state(true);
</script>

{#if loggedIn}
  <p>Welcome back!</p>
{:else}
  <p>Please log in.</p>
{/if}

Loops

Use an {#each} block to display items from an array.

<script>
  let languages = [
    "JavaScript",
    "Python",
    "Svelte",
    "Java"
  ];
</script>

<ul>
  {#each languages as language}
    <li>{language}</li>
  {/each}
</ul>

Events

Event attributes such as onclick let you run code when a user interacts with an element.

<button onclick={() => alert("Hello!")}>
  Click Me
</button>

In modern Svelte 5 code, event attributes such as onclick are the standard approach. Older tutorials may show legacy event directives such as on:click.

Forms and Two-Way Binding

Forms are used to collect information such as names, email addresses, search terms, and other user input.

The bind:value syntax connects an input element to a variable.

<script>
  let username = $state("");
</script>

<input
  bind:value={username}
  placeholder="Enter your name"
/>

<p>Name: {username}</p>

When the user types in the input, the state changes and the displayed name updates.

You can use the same approach with an email input:

<script>
  let email = $state("");
</script>

<label for="email">Email address</label>
<input
  id="email"
  type="email"
  bind:value={email}
/>

<p>Your email: {email}</p>

Real forms should also provide suitable labels, validation, helpful error messages, and secure handling of submitted information.

Svelte Stores

Svelte has a store system that can help manage shared state and subscribe to values that change over time.

Svelte 5 runes can reduce the need for stores in many situations. Stores can still be useful for particular patterns, shared reactive values, and integrations involving subscriptions or external data streams.

Choose the simplest state-management approach that fits your application's needs.

What Is SvelteKit?

SvelteKit is the application framework built around Svelte. It provides tools for building complete web applications rather than only individual interface components.

SvelteKit includes features such as:

  • File-based routing
  • Page and layout components
  • Data loading
  • Server-side rendering options
  • Server endpoints
  • Form actions
  • Deployment adapters
Simple explanation: Svelte helps you build the user interface. SvelteKit provides the application structure and additional tools needed to build a complete website.

SvelteKit Routing

SvelteKit uses file-based routing. Files and folders inside src/routes define the application's routes.

src/
└── routes/
    ├── +page.svelte
    ├── about/
    │   └── +page.svelte
    └── contact/
        └── +page.svelte

This structure can represent routes such as:

  • /
  • /about
  • /contact

Dynamic Routes

Dynamic routes are useful when a URL contains a changing value, such as a blog article slug or a product identifier.

src/routes/blog/[slug]/+page.svelte

This route pattern can represent different blog articles. The application can use the route parameter to identify the requested article.

Loading Data in SvelteKit

Web applications often need data from an API. SvelteKit provides loading functions that can fetch data and make it available to pages.

A simplified example of a page server or universal load function is:

export async function load({ fetch }) {
  const response = await fetch(
    "https://example.com/api/products"
  );

  if (!response.ok) {
    return { products: [] };
  }

  const products = await response.json();

  return { products };
}

This example illustrates the basic flow. In a real project, you should handle errors appropriately and validate the structure of data returned by the API.

What Is an API?

An API provides a way for software systems to communicate. A Svelte application may use an API to retrieve:

  • User information
  • Products and prices
  • News articles
  • Weather information
  • Sports data
  • Payment status
Security tip: Do not put private API keys, database passwords, or other secret credentials in browser-side code. Keep secrets on a trusted server and use suitable access controls.

What Is JSON?

JSON is a common format for exchanging structured information between applications and APIs.

{
  "name": "Laptop",
  "price": 800,
  "available": true
}

This example represents a product with a name, price, and availability status.

Databases and SvelteKit

A complete web application may need a database to store information such as:

  • User accounts
  • Products
  • Orders
  • Blog posts
  • Comments
  • Application settings

SvelteKit server-side code can communicate with a database using suitable database libraries, drivers, or hosted services.

Common database choices include PostgreSQL, MySQL, SQLite, and some managed database services. The right choice depends on the project.

Authentication

Authentication allows an application to identify users. Common features include:

  • Email and password login
  • Social login
  • Sessions
  • Protected pages
  • User roles and permissions
Security reminder: Never store passwords as plain text. Use a well-maintained authentication solution or secure password-hashing methods, protect sessions, and check permissions on the server.

TypeScript with Svelte

Svelte supports TypeScript, which adds static type checking to JavaScript. TypeScript can help developers catch certain mistakes and make larger projects easier to maintain.

<script lang="ts">
  type User = {
    name: string;
    age: number;
  };

  let user: User = {
    name: "Ali",
    age: 25
  };
</script>

<h2>{user.name}</h2>

The example defines a User type with a name and an age, then creates an object that follows that type.

CSS in Svelte

A Svelte component can contain its own CSS in a <style> block.

<style>
  .card {
    padding: 20px;
    border-radius: 10px;
    background: white;
  }
</style>

Component styles help keep a component's design organized. Svelte scopes component styles by default in common component-style usage.

Accessibility

A good Svelte application should be usable by people with different abilities and different ways of navigating the web.

  • Use meaningful HTML elements.
  • Add useful alternative text to informative images.
  • Provide labels for form fields.
  • Support keyboard navigation.
  • Maintain readable text and color contrast.
  • Use clear error messages.
  • Ensure interactive controls have understandable names.

Performance

Website performance affects the user experience. Consider these practices:

  • Optimize image sizes and formats.
  • Avoid unnecessary JavaScript and work in the browser.
  • Load data efficiently.
  • Use caching where appropriate.
  • Keep components focused and manageable.
  • Test the application on mobile devices and slower networks.

Deploying a SvelteKit Application

After building and testing an application, you can deploy it to a suitable hosting platform. SvelteKit uses adapters to prepare an application for different deployment environments.

A typical deployment process includes:

  1. Test the application locally or in a development environment.
  2. Build the production version.
  3. Choose a hosting platform and the appropriate adapter.
  4. Configure environment variables and secrets.
  5. Deploy the application.
  6. Test the live site and check its logs.

SvelteKit and Cloud Platforms

SvelteKit can be deployed to different environments, including Cloudflare, Netlify, Vercel, and Node.js-based servers, depending on the application's requirements and the appropriate adapter.

Before deploying, confirm that your chosen platform supports the features your application needs, including any server-side code, database connections, and environment variables.

Important: A SvelteKit application is not necessarily a collection of static HTML files. If your project needs server-side features, you must choose a hosting setup that supports them. Static deployment is suitable only when the application's requirements allow it.

Beginner Project Ideas

Building small projects is one of the most useful ways to practise Svelte.

  1. Counter application: Practise state and click events.
  2. Todo list: Practise arrays, inputs, and adding or removing tasks.
  3. Weather application: Practise API requests and loading states.
  4. Notes application: Practise forms and saving information.
  5. Blog: Practise routing and displaying content.
  6. Portfolio website: Practise reusable components and responsive design.
  7. Product catalog: Practise lists, filtering, and product cards.
  8. News website: Practise data loading and navigation.
  9. Student dashboard: Practise tables, forms, and application layouts.
  10. Simple online store: Practise product pages, cart state, and backend integration.

Simple Counter Project

This example demonstrates reactive state and click events in Svelte 5.

<script>
  let count = $state(0);
</script>

<main>
  <h1>Counter</h1>

  <p>Count: {count}</p>

  <button onclick={() => count++}>
    Increase
  </button>

  <button onclick={() => count--}>
    Decrease
  </button>

  <button onclick={() => count = 0}>
    Reset
  </button>
</main>

Try adding a reset button, a limit, or a message that changes when the count reaches a particular value.

Simple Todo Example

This example shows how to add tasks to a reactive array.

<script>
  let tasks = $state([
    "Learn JavaScript",
    "Learn Svelte"
  ]);

  let newTask = $state("");

  function addTask() {
    const task = newTask.trim();

    if (!task) return;

    tasks.push(task);
    newTask = "";
  }
</script>

<input
  bind:value={newTask}
  placeholder="New task"
/>

<button onclick={addTask}>
  Add
</button>

<ul>
  {#each tasks as task}
    <li>{task}</li>
  {/each}
</ul>

This is a learning example. A more complete todo application could also support deleting tasks, marking tasks as complete, and saving tasks between visits.

Common Beginner Mistakes

  • Trying to learn Svelte without understanding basic JavaScript.
  • Confusing Svelte with SvelteKit.
  • Mixing older syntax and modern Svelte 5 syntax without understanding the difference.
  • Not understanding reactive state.
  • Putting too much unrelated logic into one component.
  • Exposing private API keys in browser-side code.
  • Ignoring accessibility and mobile responsiveness.
  • Copying code without understanding what it does.
  • Failing to handle API errors or unexpected data.
  • Deploying without testing the production version.

Mistakes are a normal part of learning. Read error messages carefully, simplify the problem, and test one change at a time.

Security Basics

  • Keep private credentials on a trusted server.
  • Validate user input on the server where appropriate.
  • Use HTTPS in production.
  • Check permissions for protected resources.
  • Keep dependencies updated.
  • Do not trust data simply because it came from the browser.
  • Protect session cookies and authentication flows.

How to Learn Svelte Step by Step

  1. Learn basic HTML.
  2. Learn CSS and responsive design.
  3. Understand JavaScript variables, functions, arrays, objects, and promises.
  4. Learn how Svelte components work.
  5. Practise markup, conditional blocks, and loops.
  6. Learn Svelte 5 runes, beginning with $state.
  7. Learn props and component communication.
  8. Learn event handling and forms.
  9. Practise with small projects.
  10. Learn SvelteKit and file-based routing.
  11. Learn data loading and API integration.
  12. Understand databases and authentication.
  13. Learn deployment and production testing.

You do not need to master every topic before building something. Create a small project, learn from the problems you encounter, and improve it gradually.

Svelte Cheat Sheet

Concept Meaning
Svelte A compiler-based framework for building web interfaces.
Svelte 5 A major Svelte version that introduced runes.
$state Creates reactive state.
$derived Calculates a value from other values.
$effect Runs reactive side-effect logic.
$props Declares component properties.
.svelte The usual file extension for a Svelte component.
onclick An event attribute for handling click interactions.
bind:value Connects an input value to a variable.
SvelteKit An application framework built around Svelte.
+page.svelte A page component in SvelteKit routing.

Frequently Asked Questions

Is Svelte a programming language?

No. Svelte is a framework and compiler system used to build web interfaces and applications. Svelte projects commonly use JavaScript or TypeScript.

Is Svelte the same as JavaScript?

No. JavaScript is a programming language. Svelte uses JavaScript and adds its own component syntax and compiler-based development approach.

What is SvelteKit?

SvelteKit is an application framework built around Svelte. It provides features such as routing, data loading, server-side capabilities, and deployment adapters.

What are Svelte runes?

Runes are Svelte 5 syntax for expressing concepts such as reactive state, derived values, effects, and component properties.

Can I use TypeScript with Svelte?

Yes. Svelte supports TypeScript in components and application code.

Can Svelte build mobile-friendly websites?

Yes. Svelte can be used to build responsive websites that work on phones, tablets, and computers. Responsive design still needs to be implemented and tested.

Can Svelte connect to APIs?

Yes. Svelte applications can request data from APIs. SvelteKit can also provide server-side functionality for applications that need it.

Can Svelte work with databases?

Yes. Server-side code in a suitable SvelteKit deployment can connect to databases using appropriate libraries or services. Database credentials should remain private.

Is Svelte suitable for beginners?

It can be. Knowing basic HTML, CSS, and JavaScript first will make it easier to understand components, events, state, and application structure.

Can I deploy SvelteKit to Cloudflare?

Yes, SvelteKit supports deployment to Cloudflare using a suitable adapter and configuration. The correct setup depends on whether your application needs server-side features or can be deployed as a static site.

Conclusion

Svelte is a modern way to build web interfaces using components, HTML, CSS, and JavaScript or TypeScript. Its compiler-based approach and component syntax can help developers create interactive applications.

Svelte 5 introduces runes such as $state, $derived, $effect, and $props for working with state, derived values, side effects, and component properties.

When you need a complete web application, SvelteKit provides features such as routing, data loading, server-side capabilities, and deployment adapters.

Best way to learn: Start with a counter, build a todo list, practise forms and components, and then move on to APIs, databases, and complete applications.

Keep practising, read the documentation, and build projects that solve real problems.

For the latest syntax and framework features, consult the official Svelte documentation at svelte.dev/docs.

↑ Back to top