Getting started with SvelteKit || Server side rendering

Getting started with SvelteKit || Server side Rendering

Github : https://github.com/tkssharma/lets-play-with-sveltejs Playlist : https://www.youtube.com/watch?v=lxzyI4WoffM&list=PLT5Jhb7lgSBMqIuNda0gGNEiMS-ahGJM1

SvelteKit is a framework for building extremely high-performance web apps.

Building an app with all the modern best practices is fiendishly complicated. Those practices include build optimizations, so that you load only the minimal required code; offline support; prefetching pages before the user initiates navigation; and configurable rendering that allows you to generate HTML on the server or in the browser at runtime or at build-time. SvelteKit does all the boring stuff for you so that you can get on with the creative part.

It uses Vite with a Svelte plugin to provide a lightning-fast and feature-rich development experience with Hot Module Replacement (HMR), where changes to your code are reflected in the browser instantly.

You don't need to know Svelte to understand the rest of this guide, but it will help. In short, it's a UI framework that compiles your components to highly optimized vanilla JavaScript. Read the introduction to Svelte blog post and the Svelte tutorial to learn more.

Getting started

The easiest way to start building a SvelteKit app is to run npm init:

To get started, open up a new terminal window and initiate your svelte application using the command below. Note if you don't have npm installed, you'll need to get it. You can install npm by installing Node.JS, via the link here.

Once you have Node.JS and NPM installed, run the command below. Before you do that though, make sure you use cd to move into the folder you want to create your new Svelte application in.

npm init svelte@next my-svelte-app

➜  lets-play-with-sveltejs git:(master) npm init svelte@next

npx: installed 5 in 0.874s

create-svelte version 2.0.0-next.136

Welcome to SvelteKit!

This is beta software; expect bugs and missing features.

Problems? Open an issue on https://github.com/sveltejs/kit/issues if none exists already.

✔ Where should we create your project?
  (leave blank to use current directory) … 
✔ Directory not empty. Continue? … yes
✔ Which Svelte app template? › SvelteKit demo app
✔ Add type checking? › TypeScript
✔ Add ESLint for code linting? … No / Yes
✔ Add Prettier for code formatting? … No / Yes
✔ Add Playwright for browser testing? … No / Yes

Your project is ready!
✔ Typescript
  Inside Svelte components, use <script lang="ts">
✔ ESLint
  https://github.com/sveltejs/eslint-plugin-svelte3
✔ Prettier
  https://prettier.io/docs/en/options.html
  https://github.com/sveltejs/prettier-plugin-svelte#options
✔ Playwright
  https://playwright.dev

Install community-maintained integrations:
  https://github.com/svelte-add/svelte-adders

Next steps:
  1: npm install (or pnpm install, etc)
  2: git init && git add -A && git commit -m "Initial commit" (optional)
  3: npm run dev -- --open

To close the dev server, hit Ctrl-C

Stuck? Visit us at https://svelte.dev/chat

When you run this command, you'll auto generate a Svelte template in a folder called my-svelte-app. Svelte will guide you through a number of options. Select your preferences. The image below shows the one's I have selected. For the purposes of this guide, I will be using the Skeleton project.

Options for Selecting in SvelteKit

Finally, run the following command to cd into your svelte directory:

cd my-svelte-app

And then install all of your dependencies using the following line:

npm i

Svelte File Structure

If you are familiar with other frameworks, then Svelte will feel familiar. Here is an overview of the file structure in Svelte, for the project we have just made:

static                 <-- where we store all of our public assets like favicons, images, and fonts
|- favicon.png         <-- our favicon
tests                  <-- a folder to store our tests
|- test.js             <-- an example test using @playwright
src                    <-- our main Svelte app files
|- routes              <-- a folder to store all of our routes in
|-- index.svelte       <-- our index route file. This will be the file displayed at the route of the site
|- app.d.ts            <-- our core Svelte app file
|- app.html            <-- our main index file where the app will appear
.gitignore             <-- files we wish to ignore for git
.npmrc                 <-- config file for npm
.prettierrc            <-- config file for prettier
.eslintrc.cjs          <-- config file for eslint
package.json           <-- our NPM installed packages
playwright.config.js   <-- config file for playwright
svelte.config.js       <-- config file for svelte itself
tsconfig.json          <-- config file for typescript

Our basic Svelte application is ready to go. If you want to see how it looks, you can serve it on your local computer on the URL http://localhost:3000 by running the following command in your Svelte application folder:

npm run dev

If you visit http://localhost:3000 in your browser, you should see something like this:

Our first Svelte Application

Creating new pages or routes in Svelte

To make a new route in Sveltekit, simply make a new file within the routes folder. For example, if you make a file called about.svelte, then it will show up at http://localhost:3000/about. Another way you can do this is to make a new folder called about, and put index.svelte in that folder, http://localhost:3000/about will work.

Try it yourself Create a new page within your /src/routes folder, called about.svelte. Now when you go to http://localhost:3000/, you will be able to access that page. Similarly, you can try making a folder called about with a file placed inside called index.svelte

How to run your SvelteKit App on Node.JS

To run your Svelte application on a server or locally on a Node.JS server, you need to use an adapter. If you want to run your Svelte application on a Node Server, install @sveltejs/adapter-node@next via the following line:

npm i @sveltejs/adapter-node@next 

Now we have to change our svelte.config.js file. We need to use the new adapter, and change our kit.adapter object within the config file. You can replace the contents of your svelte.config.js with the code below, but we're only changing two lines - our adapter import, and then adding the build directory in your config: // We have changed the adapter line to use adapter-node@next import adapter from '@sveltejs/adapter-node@next'; import preprocess from 'svelte-preprocess';

/** @type {import('@sveltejs/kit').Config} */
const config = {
    // Consult https://github.com/sveltejs/svelte-preprocess
    // for more information about preprocessors
    preprocess: preprocess(),

    kit: {
        // We have changed this to point to a build directory
        adapter: adapter({ out: 'build' })
    }
};
export default config;

SvelteKit then does all the heavy lifting of setting up an app with server-side rendering, routing, and more, just like Next.js. However, SvelteKit also uses an adapter that can export your app to a specific platform and adapts well to serverless architecture. Since serverless architecture is becoming more prominent, it’s a good reason to try SvelteKit out.

You can use the official SvelteKit adapters for platforms like Netlify and Vercel.

By also providing features including server-side rendering, code splitting, and more, SvelteKit is especially useful for beginnings.

SvelteKit sets up a routing system where files in your src/routes determine the routes in your app. This directory can be changed by editing svelte.config.cjs.

Note that src/routes/index.svelte is the homepage.

By inputting npm run dev, you start a development server. SvelteKit uses Vite behind the scenes making updates are blazing fast.

At this point, install the static adapter to build the pre-rendered version of the entire app by using the following:

We will add another route to the counter app that SvelteKit bootstrapped for us by inputting about.svelte to the src/routes/ directory.

<!-- about page -->
<svelte:head>
    <title>About</title>
</svelte:head>
<h1>About Page</h1>
<p>This is the about page. Click <a href="/">here</a> to go to the index page.</p>

As you can probably guess, this will set up another route for us at /about. To navigate to this page, we will add a link to the index page as well.

The index page already has the following line:

Visit svelte.dev to learn how to build Svelte apps.

We’ll just change it to the code below:

Visit the about page

When we click on the link, the internal router kicks in and handles the navigation. In fact, SvelteKit handles the navigation by default. The initial load is handled on the server side, then SvelteKit’s inbuilt router handles the subsequent navigation on the client side unless we specify otherwise.

SvelteKit allows you to disable this router by altering the Svelte configuration file svelte.config.cjs. Setting the router property to false disables the app-wide router. This will cause the app to send new requests for each page, meaning the navigation will be handled on the server side.

Conclusion

In this guide we've looked at how to use SvelteKit to create your first Svelte application with routes. Let's look at what we've learned:

How to set up SvelteKit and create the basic structure of your Svelte application. How to use routes in SvelteKit, so you can have multiple pages on your application. How to update your config file to use the right adapter, based on where you want to deploy your application. How to build and run your application locally on a Node.JS server.

Comments