SvelteKit is a relatively new SSR framework for SvelteJS. We can compare it to NextJS, but instead of using React, it uses Svelte. In this tutorial, you'll learn how you can create a blog website with SvelteKit and Strapi as a CMS.
SvelteKit is a relatively new SSR framework for SvelteJS. We can compare it to NextJS, but instead of using React, it uses Svelte. In this tutorial, you'll learn how you can create a blog website with SvelteKit and Strapi as a CMS.
A Content Management System (CMS) is a popular tool for creating web pages, blogs, and online stores. They store your website's data, images, pictures, and other hosted content. They are popular among bloggers because anyone can spin up a blog pretty quickly.
Strapi is a headless CMS coded in Javascript. A headless CMS has no frontend, only an admin panel, so it is ideal for developers. In other words, a Headless CMS is an API that serves up your content to be consumed by a frontend.
In this tutorial, you'll code a blog website using the SvelteKit framework. You'll use Strapi for content management.
You'll learn how to use Strapi to manage your content and the basics of SvelteKit, including:
Now that you know what a CMS and Strapi are, you can get started by locally hosting Strapi, or in other words, Creating a Strapi Project.
Run this command in an empty folder to create a Strapi project.
npx create-strapi-app cms --quickstart
You can replace the word cms
with anything you like. This command will be the name of the folder your new Strapi project will sit in.
Now sit back, relax, and wait for the project to create itself. After that, you should automatically be taken to localhost:1377.
If that's not the case, cd
into the newly created folder and run this command.
npm run strapi develop
This command will start Strapi up on port 1337
. If a page is not automatically opened up for you, open localhost:1377 to launch the Strapi Admin Page.
It should present you with this page. You need to sign up for an account here. Remember that this account is locally-scoped to this project, meaning it won't work on other Strapi projects.
In the sidebar of Strapi admin http://localhost:1377
, click the Content-Types Builder
button. This button should take you to the Content Types builder page.
We can compare a content type to a table in SQL. Thus, content types help us structure and categorize our data.
Let's create a content type for posts. Then, click the Create new Collection Type
button to launch a dialogue.
Enter Post
as the name. Go to Advanced Settings
at the top and disable the Drafts system. Click Continue
Add these fields. Refer to the image if you get stuck.
title
field with type Text
.description
field with type Text
. Make sure the text is Long text
.content
field with the Rich Text
type.Let's also add a relation between Post
and User from the users-permissions
plugin. This relationship allows us to easily link a post to a user to display relevant information like the Author's name and profile picture, fetch the Author's posts, etc.
Add a new Relation
field to the Post
content type. The column on the left should be PostPost, and the column on the right should be User from users-permissions
. Select the fourth relation; the User
has many Posts
and clicks Finish
.
Refer to the below image if you get stuck:
Click Save
to save your changes and restart the server.
Next, we will be adding a dynamic autogenerated slug system to the Post
collection type. Using a slug will make it easier to query for our posts in the frontend.
First, navigate to Content-Types Builder and click Post, then click Add another field. Select UID. Set the field slug
, and set the attached field to title
. Save your changes and click Configure the view, and select the slug
field.
Then, set the Editable field off in the window that appears. Click Save to register your changes.
With the slug system fully set up, a new slug will be automatically generated in an uneditable slug field anytime you create a new product. The Slug will be created from the product name.
If you try querying the Content API for the posts
content type, i.e., at http://localhost:1377/api/posts
, you'll get a 403 FORBIDDEN
error.
This error is because, by default, Strapi doesn't allow any man down the street to access your content. You're supposed to set rules and permissions for specific roles. Let's allow the Public
role, i.e., an unauthenticated user, to read our posts.
In the sidebar, click on the Settings
button. There, click on Roles
in the Users & Permissions
section. But, first, let's edit the permissions for the Public role.
We'll allow the Public
role to count
, find
and findOne
for Posts.
Next, let's do the same for the Authenticated
role, but we'll also allow them to create, update and delete posts as well.
Now for the main SvelteKit code. Create a new folder named frontend
in the same directory as the folder for the Strapi project and cd
into it.
Now, let's create a SvelteKit project with this command:
npm init svelte@next
Add your preferred project name, and be sure to choose the options as shown in the below image.
Launch the app inside your favourite editor, for example, VSCode. Now, we can start the app with the below two commands:
# To install packages
npm I
# To start the app
npm run dev
Here's how your app should look, hosted on localhost:3000
TailwindCSS is a straightforward way to style your apps, and it's clear to add them to SvelteKit.
We'll use SvelteAdd to add TailwindCSS to our application quickly. Run the below command to add TailwindCSS to our project.
npx svelte-add tailwindcss
Install the required dependencies.
npm i
Be sure to stop the running server with Ctrl+C
first.
Let's start our project from scratch.
Delete all the extra CSS, except the @tailwind
parts in src/app.css
. Delete all of the items in src/routes
and src/lib
, and now we should be left with an empty project.
Create a new file src/routes/index.svelte
. All files in the src/routes
folder will be mapped to actual routes. For example, src/routes/example.svelte
will be accessible at /example
, and src/routes/blog/test.svelte
will be accessible at /blog/test
. index.svelte
is a special file. It maps to the base directory. src/routes/index.svelte
maps to /
, and src/routes/blog/index.svelte
maps to /blog
.
This is how filesystem based routing works in SvelteKit. Later, you'll learn to add routes with dynamic names.
For now, let's work on the basic UI. Add the following code to index.svelte
1 <script lang="ts">
2 </script>
3
4 <div class="my-4">
5 <h1 class="text-center text-3xl font-bold">My wonderful blog</h1>
6 </div>
I've elected to use Typescript, which is just like Javascript, but with types. You can follow along with javascript, but types and interfaces won't work for you. Also, you shouldn't put lang="ts" in your script tag.`
Now you'll notice that TailwindCSS is no longer working. This is because we deleted __layout.svelte
, the file importing src/app.css
. Let's now learn what this __layout.svelte
file is.
__layout.svelte
is a special file that adds a layout to every page. __layout.svelte
s can not only exist at the top level routes
folder, but can also exist in subdirectories, applying layouts for that subdirectory.
Read more about SvelteKit layouts here.
For now, all we have to do, is create src/routes/__layout.svelte
and import src/app.css
in it. The
Now here, in this __layout.svelte
file, we can add whatever content we want, and it'll be displayed on all pages. So, add your Navbars, Headers, Footers, and everything else here.
Here is what your app should look like now at localhost:3000
Now, we can fetch blog posts from Strapi and display them in index.svelte
. We'll utilize SvelteKit Endpoints to make API fetching easier. Endpoints in SvelteKit are files ending with .js
(or .ts
for typescript) that export functions corresponding to HTTP methods. These endpoint files become API routes in our application.
Let's create an endpoint src/routes/posts.ts
(use the .js
extension if you're not using typescript)
1 // src/routes/posts.ts
2 import type { EndpointOutput } from '@sveltejs/kit';
3 export async function get(): Promise<EndpointOutput> {
4 const res = await fetch('http://localhost:1337/api/posts?populate=*');
5 const data = await res.json();
6 return { body: data };
7 }
8 #Ignore the typings if you're using javascript.
Now, when we visit http://localhost:3000/posts
, we'll receive the posts from Strapi. Let's implement this route in our index.svelte
file using SvelteKit's Loading functionality.
Loading allows us to fetch APIs before the page is loaded using a particular <script context=" module">
tag.
Add this to the top of src/routes/index.svelte
.
1 <script lang="ts" context="module">
2 import type { Load } from '@sveltejs/kit';
3 import { goto } from '$app/navigation';
4 export const load: Load = async ({ fetch }) => {
5 const res = await fetch('/posts');
6 const response = await res.json();
7 return { props: { posts: response.data } };
8 };
9 </script>
10 <script lang="ts">
11 export let posts: any;
12 </script>
You can see that the load
function takes in the fetch
function provided to us by SvelteKit and returns an object containing props
. These props are passed down to our components.
1 <script lang="ts" context="module">
2 import type { Load } from '@sveltejs/kit';
3 import { goto } from '$app/navigation';
4 export const load: Load = async ({ fetch }) => {
5 const res = await fetch('/posts');
6 const response = await res.json();
7 return { props: { posts: response.data } };
8 };
9 </script>
10 <script lang="ts">
11 export let posts: any;
12 </script>
13 <div class="my-4">
14 <h1 class="text-center text-3xl font-bold">My wonderful blog</h1>
15 </div>
16 <div class="container mx-auto mt-4">
17 {#each posts as post}
18 <div
19 class="hover:bg-gray-200 cursor-pointer px-6 py-2 border-b border-gray-500"
20 on:click={() => goto('/blog/' + post.id)}
21 >
22 <h4 class="font-bold">{post.attributes.title}</h4>
23 <p class="mt-2 text-gray-800">{post.attributes.description}</p>
24 <p class="text-gray-500">By: {post.attributes.author.data.attributes.username}</p>
25 </div>
26 {/each}
27 </div>
I've added a few typings in src/lib/types.ts
. You can check it out in the Source Code. SvelteKit allows us to access any file in src/lib using the $lib alias.
I added a test user and a test post in Strapi, and this is how my app looks.
Now, let's add a route that'll allow us to view a post. Now, you'll learn about Dynamic Routes in SvelteKit.
If we enclose a string in brackets ([])
in a filename of a route, that becomes a parameter. So, for example, if I have a route called src/routes/blog/[post].svelte
, the route maps to /blog/ANY_STRING
where ANY_STRING
will be the value of the post
parameter. Let's use this to query posts with Strapi.
We can use the load
function we talked about earlier to get the parameters. Create a file called src/routes/blog/[id].svelte
and add the below code to it.
1 <!-- src/routes/blog/[id].svelte -->
2 <script lang="ts" context="module">
3 import type { Load } from '@sveltejs/kit';
4 export const load: Load = async ({ params, fetch }) => {
5
6 // Now, we'll fetch the blog post from Strapi
7 const res = await fetch(`http://localhost:1337/api/posts/${params.id}?populate=*`);
8 // A 404 status means "NOT FOUND"
9 if (res.status === 404) {
10 // We can create a custom error and return it.
11 // SvelteKit will automatically show us an error page that we'll learn to customise later on.
12 const error = new Error(`The post with ID ${id} was not found`);
13 return { status: 404, error };
14 } else {
15 const response = await res.json();
16 return { props: { post: response.data.attributes } };
17 }
18 };
19 </script>
20 <script lang="ts">
21 import type { Post } from '$lib/types';
22 import { onMount } from 'svelte';
23 export let post: Post;
24 let content = post.content;
25 onMount(async () => {
26 // Install the marked package first!
27 // Run this command: npm i marked
28 // We're using this style of importing because "marked" uses require, which won't work when we import it with SvelteKit.
29 // Check the "How do I use a client-side only library" in the FAQ: https://kit.svelte.dev/faq
30 const marked = (await import('marked')).default;
31 content = marked(post.content);
32 });
33 </script>
34 <h1 class="text-center text-4xl mt-4">{post.title}</h1>
35 <p class="text-center mt-2">By: {post.author.data.attributes.username}</p>
36 <div class="border border-gray-500 my-4 mx-8 p-6 rounded">
37 {@html content}
38 </div>
39
We need to use the @html directive when we want the content to be actually rendered as HTML.
When you go to a blog page, you should see something like this:
Let's get started with authenticating users to our blog. Strapi allows us to configure third-party providers like Google, but we'll stick to the good ol' email and password sign-in.
We don't want anybody to register to our blog, so we'll manually create a user with Strapi. Then, in the Strapi admin panel, click on the Users
collection type in the sidebar.
There, click Add new Users
and create your user. Here's mine, for example.
Click Save
when done
We can test logging in to our user by sending a POST
request to http://localhost:1337/auth/local. Follow the image below for the correct JSON body.
The REST client I'm using in the above image is Postman.
Let's create a new route src/routes/login.svelte
. This will of course map to /login
.
1 <script lang="ts">
2 import type { User } from '$lib/types';
3 import { goto } from '$app/navigation';
4 import user from '$lib/user';
5 let email = '';
6 let password = '';
7 async function login() {
8 const res = await fetch('http://localhost:1337/api/auth/local', {
9 method: 'POST',
10 headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
11 body: JSON.stringify({ identifier: email, password })
12 });
13 if (res.ok) {
14 const data: {user: User, jwt: string} = await res.json();
15 localStorage.setItem("token", data.jwt)
16 if (data) {
17 $user = data.user;
18 goto('/');
19 }
20 } else {
21 const data: { message: { messages: { message: string }[] }[] } = await res.json();
22 if (data?.message?.[0]?.messages?.[0]?.message) {
23 alert(data.message[0].messages[0].message);
24 }
25 }
26 }
27 </script>
28 <form on:submit|preventDefault={login} class="container mx-auto my-4">
29 <h1 class="text-center text-2xl font-bold">Login</h1>
30 <div class="my-1">
31 <label for="email">Email</label>
32 <input type="email" placeholder="Enter your email" bind:value={email} />
33 </div>
34 <div class="my-1">
35 <label for="password">Password</label>
36 <input type="password" placeholder="Enter your password" bind:value={password} />
37 </div>
38 <div class="my-3">
39 <button class="submit" type="submit">Login</button>
40 </div>
41 </form>
42 <style lang="postcss">
43 label {
44 @apply font-bold block mb-1;
45 }
46 input {
47 @apply bg-white w-full border border-gray-500 rounded outline-none py-2 px-4;
48 }
49 .submit {
50 @apply bg-blue-500 text-white border-transparent rounded px-4 py-2;
51 }
52 </style>
I've created a store in src/lib/user.ts
that will house the User to access the User in any component.
Here's the code:
1 import { writable } from 'svelte/store';
2 import type { User } from './types';
3 const user = writable<User | null>(null);
4 export default user;
Great! Our /login
page works flawlessly, but there's one problem - When we refresh the page, the user store gets reset to null
. To fix this, we need to re-fetch the User every time the page reloads. That's right, we need a load
function in __layout.svelte
since it is present on every page.
Change __layout.svelte
to this code:
1 <!-- src/routes/__layout.svelte -->
2 <script lang="ts">
3 import '../app.css';
4 import userStore from '$lib/user';
5 import type { User } from '$lib/types';
6 import { onMount } from 'svelte';
7 let loading = true;
8 onMount(async () => {
9 // Check if 'token' exists in localStorage
10 if (!localStorage.getItem('token')) {
11 loading = false;
12 return { props: { user: null } };
13 }
14 // Fetch the user from strapi
15 const res = await fetch('http://localhost:1337/api/auth/me', {
16 headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
17 });
18 const user: User = await res.json();
19 loading = false;
20 if (res.ok) {
21 $userStore = user;
22 }
23 });
24 </script>
25 {#if !loading}
26 <slot />
27 {/if}
Wait a minute! Why are we using onMount
instead of load
? Since load
is executed on the server, we won't have access to localStorage
, which is on the browser. Hence, we have to wait for the app to load before accessing localStorage
.
If you visit your app, you'll get a 404
Error when trying to get the User from Strapi. This error is because /auth/me
isn't a valid route. So let's create it ourselves.
Open the Strapi project in your favorite editor. Strapi allows us to add custom API routes to it. Let's use the strapi
CLI to generate a route.
Run the following command to start the CLI.
npx strapi generate
Select controller
and add controller name Auth
. Also, click to add the new controller to a new API.
You'll find a new file called /src/api/auth/controllers/Auth.js
. We need to add our simple controller here.
Update the /src/api/auth/controllers/Auth.js
file code with the following code snippet.
1 "use strict";
2
3 /**
4 * A set of functions called "actions" for `auth`
5 */
6
7 module.exports = {
8 async me(ctx) {
9 if (ctx.state.user) {
10 return ctx.state.user;
11 }
12
13 ctx.unauthorized("You're not logged in");
14 },
15 };
This simple API route will return the User if it exists or give us a 401 UNAUTHORIZED
error.
Now, we need to tell Strapi to register this controller at /auth/me
.
To do that, create file /src/api/auth/config/routes.json
, and add the following code snippet to the file.
1 {
2 "routes": [
3 {
4 "method": "GET",
5 "path": "/auth/me",
6 "handler": "Auth.me",
7 "config": {
8 "policies": []
9 }
10 }
11 ]
12 }
Now, if we access /auth/me
, we get 404 NotFoundError
.
Like the post
routes, Strapi doesn't, by default, allow anyone to access this route either. So, let's edit permissions like how we did earlier for the Authenticated
role.
And now, everything should work flawlessly.
Let's add a quick navbar to our app. Create file src/lib/Navbar.svelte
and put the below code in it.
1 <!-- src/lib/Navbar.svelte -->
2 <script lang="ts">
3 import user from './user';
4 </script>
5 <nav class="bg-white border-b border-gray-500 py-2 px-4 w-full">
6 <div class="flex items-center justify-between container mx-auto">
7 <a href="/" class="font-bold no-underline">My blog</a>
8 <section>
9 {#if !$user}
10 <a href="/login" class="font-mono no-underline">Login</a>
11 {:else}
12 <a href="/new" class="font-mono no-underline mr-3">New</a>
13 <span class="font-mono text-gray-500">{$user.username}</span>
14 {/if}
15 </section>
16 </div>
17 </nav>
Add the Navbar to __layout.svelte
.
1 <!-- src/routes/__layout.svelte -->
2 <script lang="ts">
3 // ...
4 import Navbar from "$lib/Navbar.svelte";
5 </script>
6
7 <Navbar />
8 <slot />
Now, let's get to the juicy part. Add a file called src/routes/new.svelte
. This file will contain the form used to create a new post on Strapi.
1 <!-- src/routes/new.svelte -->
2 <script lang="ts" context="module">
3 import type { Load } from '@sveltejs/kit';
4 import type { Post } from '$lib/types';
5 export const load: Load = async ({ fetch, page: { query } }) => {
6 // edit will be an optional query string parameter that'll contain the ID of the post that needs to be updated.
7 // If this is set, the post will be updated instead of being created.
8 const edit = query.get('edit');
9 if (edit) {
10 const res = await fetch('http://localhost:1337/api/posts/' + edit);
11 if (res.status === 404) {
12 const error = new Error(`The post with ID ${edit} was not found`);
13 return { status: 404, error };
14 } else {
15 const data: Post = await res.json();
16 return {
17 props: {
18 editId: edit,
19 title: data.attributes.title,
20 content: data.attributes.content,
21 description: data.attributes.description
22 }
23 };
24 }
25 }
26 return { props: {} };
27 };
28 </script>
29 <script lang="ts">
30 import { onMount } from 'svelte';
31 import user from '$lib/user';
32 import { goto } from '$app/navigation';
33 export let editId: string;
34 export let title = '';
35 export let description = '';
36 export let content = '';
37 onMount(() => {
38 if (!$user) goto('/login');
39 });
40 // To edit the post
41 async function editPost() {
42 if (!localStorage.getItem('token')) {
43 goto('/login');
44 return;
45 }
46 const res = await fetch('http://localhost:1337/api/posts/' + editId, {
47 method: 'PUT',
48 headers: {
49 'Content-Type': 'application/json',
50 Accept: 'application/json',
51 Authorization: 'Bearer ' + localStorage.getItem('token')
52 },
53 body: JSON.stringify({ title, description, content })
54 });
55 if (!res.ok) {
56 const data: { message: { messages: { message: string }[] }[] } = await res.json();
57 if (data?.message?.[0]?.messages?.[0]?.message) {
58 alert(data.message[0].messages[0].message);
59 }
60 } else {
61 const data: Post = await res.json();
62 goto('/blog/' + data.id);
63 }
64 }
65 async function createPost() {
66 if (!localStorage.getItem('token')) {
67 goto('/login');
68 return;
69 }
70 if (editId) {
71 // We're supposed to edit, not create
72 editPost();
73 return;
74 }
75 const res = await fetch('http://localhost:1337/api/posts', {
76 method: 'POST',
77 headers: {
78 'Content-Type': 'application/json',
79 Accept: 'application/json',
80 Authorization: 'Bearer ' + localStorage.getItem('token')
81 },
82 body: JSON.stringify({ title, description, content })
83 });
84 if (!res.ok) {
85 const data: { message: { messages: { message: string }[] }[] } = await res.json();
86 if (data?.message?.[0]?.messages?.[0]?.message) {
87 alert(data.message[0].messages[0].message);
88 }
89 } else {
90 const data: Post = await res.json();
91 goto('/blog/' + data.id);
92 }
93 }
94 </script>
95 <form on:submit|preventDefault={createPost} class="my-4 mx-auto container p-4">
96 <div class="my-1">
97 <label for="title">Title</label>
98 <input type="text" placeholder="Enter title" id="title" bind:value={title} />
99 </div>
100 <div class="my-1">
101 <label for="description">Description</label>
102 <input type="text" placeholder="Enter description" id="description" bind:value={description} />
103 </div>
104 <div class="my-1">
105 <label for="title">Content</label>
106 <textarea rows={5} placeholder="Enter content" id="content" bind:value={content} />
107 </div>
108 <div class="my-2">
109 <button class="submit" type="submit">Submit</button>
110 </div>
111 </form>
112 <style lang="postcss">
113 label {
114 @apply font-bold block mb-1;
115 }
116 input {
117 @apply bg-white w-full border border-gray-500 rounded outline-none py-2 px-4;
118 }
119 textarea {
120 @apply bg-white w-full border border-gray-500 rounded outline-none py-2 px-4 resize-y;
121 }
122 .submit {
123 @apply bg-blue-500 text-white border-transparent rounded px-4 py-2;
124 }
125 </style>
Don't try this out yet, since there's currently no way to determine the Author of the PostPost. We need to code that in Strapi explicitly.
Let's create custom controllers for the Post
content type. Here, we'll make it so that the Author of a post will be the currently logged-in User.
Edit api/post/controllers/post.js
in the Strapi project.
1 'use strict';
2 /**
3 * post controller
4 */
5 const { createCoreController } = require('@strapi/strapi').factories;
6 const { parseMultipartData, sanitizeEntity } = require("strapi-utils");
7 /**
8 * Read the documentation (https://docs.strapi.io/developer-docs/latest/development/backend-customization.html#core-controllers)
9 * to customize this controller
10 */
11 module.exports = {
12 async create(ctx) {
13 let entity;
14 if (ctx.is("multipart")) {
15 const { data, files } = parseMultipartData(ctx);
16 data.author = ctx.state.user.id;
17 entity = await strapi.services.post.create(data, { files });
18 } else {
19 ctx.request.body.author = ctx.state.user.id;
20 entity = await strapi.services.post.create(ctx.request.body);
21 }
22 return sanitizeEntity(entity, { model: strapi.models.post });
23 },
24 async update(ctx) {
25 const { id } = ctx.params;
26 let entity;
27 const [article] = await strapi.services.post.find({
28 id: ctx.params.id,
29 "author.id": ctx.state.user.id,
30 });
31 if (!article) {
32 return ctx.unauthorized(`You can't update this entry`);
33 }
34 if (ctx.is("multipart")) {
35 const { data, files } = parseMultipartData(ctx);
36 entity = await strapi.services.post.update({ id }, data, {
37 files,
38 });
39 } else {
40 entity = await strapi.services.post.update({ id }, ctx.request.body);
41 }
42 return sanitizeEntity(entity, { model: strapi.models.post });
43 },
44 async delete(ctx) {
45 const { id } = ctx.params;
46 let entity;
47 const [article] = await strapi.services.post.find({
48 id: ctx.params.id,
49 "author.id": ctx.state.user.id,
50 });
51 if (!article) {
52 return ctx.unauthorized(`You can't delete this entry`);
53 }
54 await strapi.services.post.delete({ id });
55 return { ok: true };
56 },
57 };
58 module.exports = createCoreController('api::post.post');
If you get confused, checkout the Strapi Documentation
Install strapi-utils
with the following command.
npm install strapi-utils
And now, you should be able to create and update posts all from one route. Let's make the update process easier. Change src/routes/blog/[id].svelte
to the code below:
1 <!-- src/routes/blog/[id].svelte -->
2 <script lang="ts" context="module">
3 import type { Load } from '@sveltejs/kit';
4 export const load: Load = async ({ params, fetch }) => {
5
6 // Now, we'll fetch the blog post from Strapi
7 const res = await fetch(`http://localhost:1337/api/posts/${params.id}?populate=*`);
8 // A 404 status means "NOT FOUND"
9 if (res.status === 404) {
10 // We can create a custom error and return it.
11 // SvelteKit will automatically show us an error page that we'll learn to customise later on.
12 const error = new Error(`The post with ID ${params.id} was not found`);
13 return { status: 404, error };
14 } else {
15 const response = await res.json();
16 return { props: { post: response.data.attributes } };
17 }
18 };
19 </script>
20 <script lang="ts">
21 import type { Post } from '$lib/types';
22 import { onMount } from 'svelte';
23 import { goto } from '$app/navigation';
24 import user from '$lib/user';
25 export let post: Post;
26 let content = post.content;
27 onMount(async () => {
28 // Install the marked package first!
29 // Run this command: npm i marked
30 // We're using this style of importing because "marked" uses require, which won't work when we import it with SvelteKit.
31 // Check the "How do I use a client-side only library" in the FAQ: https://kit.svelte.dev/faq
32 const marked = (await import('marked')).default;
33 content = marked(post.content);
34 });
35 async function deletePost() {
36 // TODO
37 }
38 </script>
39 <h1 class="text-center text-4xl mt-4">{post.title}</h1>
40 <p class="text-center mt-2">By: {post.author.data.attributes.username}</p>
41 {#if $user && post.author.id === $user.id}
42 <p class="my-2 flex justify-center items-center gap-3">
43 <button
44 class="bg-blue-500 text-white font-bold py-2 px-4 rounded border-transparent"
45 on:click={() => goto('/new?edit=' + post.id)}>Update post</button
46 >
47 <button
48 class="bg-red-500 text-white font-bold py-2 px-4 rounded border-transparent"
49 on:click={deletePost}>Delete post</button
50 >
51 </p>
52 {/if}
53
54 <div class="border border-gray-500 my-4 mx-8 p-6 rounded">
55 {@html content}
56 </div>
Now, when the Author visits their PostPost, they'll see two buttons to Update and Delete the PostPost, respectively.
Don't try this out yet, since there's currently no way to determine the Author of the PostPost. We need to code that in Strapi explicitly.
Let's create custom controllers for the Post
content type. Here, we'll make it so that the Author of a post will be the currently logged-in User.
Edit api/post/controllers/post.js
in the Strapi project.
1 "use strict";
2
3 const { parseMultipartData, sanitizeEntity } = require("strapi-utils");
4
5 /**
6 * Read the documentation (https://docs.strapi.io/developer-docs/latest/development/backend-customization.html#core-controllers)
7 * to customize this controller
8 */
9
10 module.exports = {
11 async create(ctx) {
12 let entity;
13
14 if (ctx.is("multipart")) {
15 const { data, files } = parseMultipartData(ctx);
16 data.author = ctx.state.user.id;
17 entity = await strapi.services.post.create(data, { files });
18 } else {
19 ctx.request.body.author = ctx.state.user.id;
20 entity = await strapi.services.post.create(ctx.request.body);
21 }
22
23 return sanitizeEntity(entity, { model: strapi.models.post });
24 },
25
26 async update(ctx) {
27 const { id } = ctx.params;
28
29 let entity;
30
31 const [article] = await strapi.services.post.find({
32 id: ctx.params.id,
33 "author.id": ctx.state.user.id,
34 });
35
36 if (!article) {
37 return ctx.unauthorized(`You can't update this entry`);
38 }
39
40 if (ctx.is("multipart")) {
41 const { data, files } = parseMultipartData(ctx);
42 entity = await strapi.services.post.update({ id }, data, {
43 files,
44 });
45 } else {
46 entity = await strapi.services.post.update({ id }, ctx.request.body);
47 }
48
49 return sanitizeEntity(entity, { model: strapi.models.post });
50 },
51 };
If you get confused, checkout the Strapi Documentation
And now, you should be able to create and update posts all from one route. Let's make the update process easier. Change src/routes/blog/[slug].svelte
to the code below:
1 <!-- src/routes/blog/[slug].svelte -->
2 <script lang="ts" context="module">
3 import type { Load } from '@sveltejs/kit';
4
5 export const load: Load = async ({ page: { params }, fetch }) => {
6 // The params object will contain all of the parameters in the route.
7 const { slug } = params;
8
9 // Now, we'll fetch the blog post from Strapi
10 const res = await fetch('http://localhost:1337/posts/' + slug);
11
12 // A 404 status means "NOT FOUND"
13 if (res.status === 404) {
14 // We can create a custom error and return it.
15 // SvelteKit will automatically show us an error page that we'll learn to customise later on.
16 const error = new Error(`The post with ID ${slug} was not found`);
17 return { status: 404, error };
18 } else {
19 const data = await res.json();
20 return { props: { post: data } };
21 }
22 };
23 </script>
24
25 <script lang="ts">
26 import type { Post } from '$lib/types';
27 import { onMount } from 'svelte';
28 import { goto } from '$app/navigation';
29 import user from '$lib/user';
30
31 export let post: Post;
32 let content = post.content;
33
34 onMount(async () => {
35 // Install the marked package first!
36 // Run this command: npm i marked
37
38 // We're using this style of importing because "marked" uses require, which won't work when we import it with SvelteKit.
39 // Check the "How do I use a client-side only library" in the FAQ: https://kit.svelte.dev/faq
40 const marked = (await import('marked')).default;
41 content = marked(post.content);
42 });
43
44 async function deletePost() {
45 // TODO
46 }
47 </script>
48
49 <h1 class="text-center text-4xl mt-4">{post.title}</h1>
50 <p class="text-center mt-2">By: {post.author.username}</p>
51
52 {#if $user && post.author.id === $user.id}
53 <p class="my-2 flex justify-center items-center gap-3">
54 <button
55 class="bg-blue-500 text-white font-bold py-2 px-4 rounded border-transparent"
56 on:click={() => goto('/new?edit=' + post.id)}>Update post</button
57 >
58 <button
59 class="bg-red-500 text-white font-bold py-2 px-4 rounded border-transparent"
60 on:click={deletePost}>Delete post</button
61 >
62 </p>
63 {/if}
64
65 <div class="border border-gray-500 my-4 mx-8 p-6 rounded">
66 {@html content}
67 </div>
Now, when the Author visits their PostPost, they'll see two buttons to Update and Delete the PostPost, respectively.
Let's add functionality to the Delete Post
button. Edit the deletePost()
function in the file we just modified (src/routes/blog/[id].svelte
) and change it to this:
1 async function deletePost() {
2 if (!localStorage.getItem('token')) {
3 goto('/login');
4 return;
5 }
6 const res = await fetch('http://localhost:1337/api/posts/' + post.id, {
7 method: 'DELETE',
8 headers: { Authorization: 'Bearer ' + localStorage.getItem('token') }
9 });
10 if (res.ok) {
11 goto('/');
12 } else {
13 const data: { message: { messages: { message: string }[] }[] } = await res.json();
14 if (data?.message?.[0]?.messages?.[0]?.message) {
15 alert(data.message[0].messages[0].message);
16 }
17 }
18 }
Now, obviously, we don't want anybody to delete a post by someone else. Let's add another method in api/post/controllers/post.js
in our Strapi App.
This is how your code should look now:
1 'use strict';
2 /**
3 * post controller
4 */
5 const { createCoreController } = require('@strapi/strapi').factories;
6 const { parseMultipartData, sanitizeEntity } = require("strapi-utils");
7 /**
8 * Read the documentation (https://docs.strapi.io/developer-docs/latest/development/backend-customization.html#core-controllers)
9 * to customize this controller
10 */
11 module.exports = {
12 async create(ctx) {
13 let entity;
14 if (ctx.is("multipart")) {
15 const { data, files } = parseMultipartData(ctx);
16 data.author = ctx.state.user.id;
17 entity = await strapi.services.post.create(data, { files });
18 } else {
19 ctx.request.body.author = ctx.state.user.id;
20 entity = await strapi.services.post.create(ctx.request.body);
21 }
22 return sanitizeEntity(entity, { model: strapi.models.post });
23 },
24 async update(ctx) {
25 const { id } = ctx.params;
26 let entity;
27 const [article] = await strapi.services.post.find({
28 id: ctx.params.id,
29 "author.id": ctx.state.user.id,
30 });
31 if (!article) {
32 return ctx.unauthorized(`You can't update this entry`);
33 }
34 if (ctx.is("multipart")) {
35 const { data, files } = parseMultipartData(ctx);
36 entity = await strapi.services.post.update({ id }, data, {
37 files,
38 });
39 } else {
40 entity = await strapi.services.post.update({ id }, ctx.request.body);
41 }
42 return sanitizeEntity(entity, { model: strapi.models.post });
43 },
44 async delete(ctx) {
45 const { id } = ctx.params;
46 let entity;
47 const [article] = await strapi.services.post.find({
48 id: ctx.params.id,
49 "author.id": ctx.state.user.id,
50 });
51 if (!article) {
52 return ctx.unauthorized(`You can't delete this entry`);
53 }
54 await strapi.services.post.delete({ id });
55 return { ok: true };
56 },
57 };
58 module.exports = createCoreController('api::post.post');
And now, the author should be able to delete posts.
You may have noticed that the 404 page looks terrible. It has almost no styling. With SvelteKit, we're allowed to create a custom error page. So we need to name this file __error.svelte
and place it in src/routes
.
1 <!-- src/routes/__error.svelte -->
2 <script lang="ts" context="module">
3 import type { ErrorLoad } from '@sveltejs/kit';
4 export type { ErrorLoad } from '@sveltejs/kit';
5 export const load: ErrorLoad = ({ error, status }) => {
6 return { props: { error, status } };
7 };
8 </script>
9 <script lang="ts">
10 export let error: Error;
11 export let status: number;
12 </script>
13 <div class="fixed w-full h-full grid place-items-center">
14 <section class="p-8 border-gray-500 rounded">
15 <h1 class="text-center text-4xl font-mono-mt-4">{status}</h1>
16 <p class="text-center">{error.message}</p>
17 </section>
18 </div>
Here's how our error page will look like when you search for a blog post with wrong id.
Much better right?
Now, obviously, we don't want anybody to delete a post by someone else. Let's add another method in api/post/controllers/post.js
in our Strapi App.
This is how your code should look now:
1 // api/post/controllers/post.js
2 "use strict";
3
4 const { parseMultipartData, sanitizeEntity } = require("strapi-utils");
5
6 /**
7 * Read the documentation (https://docs.strapi.io/developer-docs/latest/development/backend-customization.html#core-controllers)
8 * to customize this controller
9 */
10
11 module.exports = {
12 async create(ctx) {
13 let entity;
14
15 if (ctx.is("multipart")) {
16 const { data, files } = parseMultipartData(ctx);
17 data.author = ctx.state.user.id;
18 entity = await strapi.services.post.create(data, { files });
19 } else {
20 ctx.request.body.author = ctx.state.user.id;
21 entity = await strapi.services.post.create(ctx.request.body);
22 }
23
24 return sanitizeEntity(entity, { model: strapi.models.post });
25 },
26
27 async update(ctx) {
28 const { id } = ctx.params;
29
30 let entity;
31
32 const [article] = await strapi.services.post.find({
33 id: ctx.params.id,
34 "author.id": ctx.state.user.id,
35 });
36
37 if (!article) {
38 return ctx.unauthorized(`You can't update this entry`);
39 }
40
41 if (ctx.is("multipart")) {
42 const { data, files } = parseMultipartData(ctx);
43 entity = await strapi.services.post.update({ id }, data, {
44 files,
45 });
46 } else {
47 entity = await strapi.services.post.update({ id }, ctx.request.body);
48 }
49
50 return sanitizeEntity(entity, { model: strapi.models.post });
51 },
52
53 async delete(ctx) {
54 const { id } = ctx.params;
55
56 let entity;
57
58 const [article] = await strapi.services.post.find({
59 id: ctx.params.id,
60 "author.id": ctx.state.user.id,
61 });
62
63 if (!article) {
64 return ctx.unauthorized(`You can't delete this entry`);
65 }
66
67 await strapi.services.post.delete({ id });
68
69 return { ok: true };
70 },
71 };
And now, the author should be able to delete posts.
And there you have it! Your blog website is made with SvelteKit and Strapi. If you got stuck anywhere, be sure to check the SvelteKit Docs, the Strapi Docs, and the source code on Github.
Quadri Sheriff is an aspiring technical writer and a software programmer. He is a very shy individual who loves writing, coding and reading in his spare time. He is currently interested in learning more about blockchain and the Jamstack.