MAIS AMOR POR FAVOR

SvelteKit FAQ Page SEO: add JSON-LD Schema

SvelteKit FAQ Page SEO

SvelteKit FAQ Page SEO: add JSON-LD Schema

SHARE:

🔑 Creating an FAQ Page with SEO Metadata in SvelteKit

In this article on SvelteKit FAQ Page SEO, we see how easy SvelteKit makes it to create an FAQ page. As well as that, we generate search engine optimised metadata. This is the stuff that increases user experience on search engine result pages and so is loved by Google, meaning your page will rank higher.

Frequently asked question (FAQ) pages are helpful when you are looking for a quick solution to a current issue and you don't want to have to read through reams of docs to extract the snippet you need. As an extra step when you create an FAQ page, it is worth also creating some metadata which tells Google about the questions and answers on the page. This is because user interaction (on the search results page) is an important ranking factor meaning your page will appear higher in search results. In this article we see how you can add the right markup to your FAQ page in SvelteKit. I hope you will find the code useful and try it out on a suitable project that you are working on.

🌟 Our Goal: FAQ Featured Snippet

SvelteKit FAQ Page SEO: image search Google result page for the query 'What is narcissus backendless'.  At top of the results is a paragraph  of text as a feature snippet directly answering this question
SvelteKit FAQ Page SEO: Google Featured Snippet

FAQ metadata on your page will prove especially useful to users who form their search query as a question. Supporting this type of search becomes increasingly import as search using mobile devices and electronic personal assistants (the likes of Alexa, Siri and friends) becomes more widespread. For example, we see in the capture above of a desktop Google search, the top result is a featured snippet. Featured snippets may also take the form of a How To. They appear large, above all results and most of all; users like to click them.

SvelteKit FAQ Page SEO: How To Example capture shows Google search results to query Create sveltekit component library.  The top result dominates listing 6 of the 10 steps needed to Create s SvelteKit Component Library
SvelteKit FAQ Page SEO: Google Featured Snippet: How To Example

Google will experiment with shuffling up search results and throwing your page to the top. If it does not get enough interaction though, it can quickly lose that prime position. It is important to remember that most users will not look beyond the first few results. So the top spaces are extremely valuable for getting users to your site.

Next we will take a peek at the SvelteKit FAQ page we are going to build featuring the meta needed for it to be considered for a featured snippet.

🧱 SvelteKit FAQ Page SEO: What we're Building

We will create a single page app. This builds on the earlier SEO tutorials where we saw how to add basic SEO metadata for search engine optimisation in SvelteKit, sharing cards for social networks and next level Schema.org SEO meta to delight search engine users and get them onto your site.

SvelteKit FAQ Page SEO: Image shows an F A Q page with the first question expanded and another two question collapsed
SvelteKit FAQ Page SEO: What we are Building

We will source our question data from a JSON file so that we can take advantage of SvelteKit JSON data imports. Once we have built the site, we will see how you can test it with Google's own SEO tools.

⚙️ SvelteKit FAQ Page SEO: Setting up the Project

To get going, spin up a skeleton SvelteKit project:

pnpm init [email protected] sveltekit-faq-page-seo && cd $_
pnpm install

You can answer no to the TypeScript prompt but, select ESLint and prettier formatting. Next we just need a couple of extra packages for this project:

pnpm add -D @fontsource/dm-sans dotenv

Then let's create a .env file in the project's root directory:

.env
plaintext
VITE_SITE_URL=https://example.com

Add the url where you will deploy the site, or just keep example.com for now, if you are not yet sure what this will be. Finally add dotenv configuration to svelte.config.js

svelte.config.js
javascript
1import 'dotenv/config';
2
3/** @type {import('@sveltejs/kit').Config} */
4const config = {
5 kit: {
6 // hydrate the <div id="svelte"> element in src/app.html
7 target: '#svelte',
8 vite: {
9 define: {
10 'process.env.VITE_BUILD_TIME': JSON.stringify(new Date().toISOString()),
11 },
12 },
13 },
14};
15
16export default conig;

The code in line 10 lets us get build time for use in the SEO meta.

⚙️ SvelteKit FAQ Page SEO: Questions

It wouldn't be much of an FAQ page without some questions, so let's create a src/lib/data folder and put an faqs.json file in there. We will import the data directly into our Svelte markup. If you want to learn more about how this works, there is a tutorial which cover s a couple of different data shapes. Anyway either paste in these questions, or add your own, keeping the same structure:

src/lib/data/faqs.json
json
1[
2 {
3 "question": "What is the deal with SvelteKit?",
4 "answer": "SvelteKit is an awesome tool for building fast websites and web apps. Its secret powers lie in the compiler at Svelte's heart. This lets Svelte generate pure JavaScript which is interpreted by the user browser. This is contrast to other frameworks where an additional step of generating JavaScript in the browser is required. SvelteKit is to Svelte what Next is to React, it is a tool for creating Svelte apps."
5 },
6 {
7 "question": "Is SvelteKit ready for production?",
8 "answer": "SvelteKit is already used in a number of production website globally."
9 },
10 {
11 "question": "Does SvelteKit use vite?",
12 "answer": "Yes. vite, like snowpack is a next generation bundler, building on advances earlier made by more established tools like WebPack. Among the advantages are faster hot module reloading and better tree shaking. These benefits come from using ES Modules."
13 },
14 {
15 "question": "Is SvelteKit still in beta?",
16 "answer": "Yes, SvelteKit is still in beta. Despite that it is already used in a number of production websites."
17 },
18 {
19 "question": "How do you deploy SvelteKit?",
20 "answer": "You can deploy SvelteKit apps as static sites or Server Side Rendered apps. Leading hosting services like Cloudflare, Netlify, Render and Vercel all support SvelteKit."
21 }
22]

You will need at least three questions for Google to consider the page to be a valid FAQ page.

🏠 SvelteKit FAQ Page SEO: Home Page

You'll see the Svelte markup is going to be quite lightweight, making it easier for you to rip this code out and insert it as a component or page in your own project. For that reason the FAQ aspects of SEO are fully working and tested but the rest of SEO is not fully fleshed out. Replace the code in src/routes/index.svelte:

src/routes/index.svelte
svelte
1<script>
2 import Question from '$lib/components/Question.svelte';
3 import SEO from '$lib/components/SEO.svelte';
4 import website from '$lib/configuration/website';
5 import faqs from '$lib/data/faqs.json';
6 import '@fontsource/dm-sans';
7
8 const { siteUrl } = website;
9 const title = 'SvelteKit FAQ Page with SEO';
10 const url = `${siteUrl}/`;
11</script>
12
13<SEO
14 {url}
15 {title}
16 {faqCount}
17 seoMetaDescription="Demo site for FAQ page using SvelteKit with SchemaOrg FAQ metadata"
18/>
19<main class="container">
20 <div class="content">
21 <h1>SvelteKit FAQs</h1>
22 <section role="feed">
23 {#each faqs as { question, answer }, index}
24 <article aria-posinset={index + 1} aria-setsize={faqCount}>
25 <Question id={`question-${index + 1}`} {question} {answer} position={index + 1} {url} />
26 </article>
27 {/each}
28 </section>
29 </div>
30</main>

If you're not new to these tutorials, you can skip to the next paragraph. Vite lets us import our JSON file and use it in the JavaScript code. You will notice the JSON file has an array at the top level and so the import in line 5 results in faqs holding that array. We can treat this just like any other array in JavaScript. In lines 2327 we iterate over the elements of the array producing a question for each one. If you are more familiar with React, consider this analogous to an array.map() method, though in Svelte there is no need to add a key to each element. Let's look at the first line of the each block. Recall each element of the array is an object with a question and answer field. We can destructure those fields from each element and also access the index using the concise notation in line 23.

This code doesn't yet work we will define the missing SEO and Question components next. Before that here is some optional styling which you can paste at the bottom of the same file:

src/routes/index.svelteclick to expand code.
src/routes/index.svelte
svelte
33<style>
34 :global(html) {
35 background-image: linear-gradient(
36 to bottom right,
37 hsl(var(--colour-dark-hue) var(--colour-dark-saturation) var(--colour-dark-luminance)),
38 hsl(
39 var(--colour-dark-hue) var(--colour-dark-saturation)
40 calc(var(--colour-dark-luminance) * 0.8)
41 )
42 );
43 color: hsl(
44 var(--colour-light-hue) var(--colour-light-saturation) var(--colour-light-luminance)
45 );
46
47 font-family: DM Sans;
48 }
49
50 :global(h1) {
51 font-size: var(--font-size-7);
52 margin-top: var(--spacing-0);
53 margin-bottom: var(--spacing-2);
54 }
55
56 :global(:root) {
57 /* paradise pink */
58 --colour-brand-hue: 345;
59 --colour-brand-saturation: 76%;
60 --colour-brand-luminance: 58%;
61
62 /* coral */
63 --colour-alt-hue: 14;
64 --colour-alt-saturation: 100%;
65 --colour-alt-luminance: 70%;
66
67 /* charleston green */
68 --colour-dark-hue: 120;
69 --colour-dark-saturation: 1%;
70 --colour-dark-luminance: 17%;
71
72 /* nickel */
73 --colour-mid-hue: 44;
74 --colour-mid-saturation: 7%;
75 --colour-mid-luminance: 41%;
76
77 /* eggshell */
78 --colour-light-hue: 49;
79 --colour-light-saturation: 60%;
80 --colour-light-luminance: 93%;
81
82 --spacing-px: 0.0625rem;
83 --spacing-px-2: 0.125rem;
84 --spacing-0: 0;
85 --spacing-1: 0.25rem;
86 --spacing-2: 0.5rem;
87 --spacing-4: 1rem;
88 --spacing-6: 1.5rem;
89 --spacing-8: 2rem;
90 --spacing-12: 3rem;
91 --spacing-20: 5rem;
92
93 --font-size-1: 1rem;
94 --font-size-2: 1.25rem;
95 --font-size-7: 3.815rem;
96 --mobile-font-size-2: 1.125rem;
97
98 --font-weight-medium: 500;
99
100 --line-height-relaxed: 1.75;
101 }
102
103 .container {
104 display: flex;
105 min-height: 100vh;
106 width: 100%;
107 }
108
109 .content {
110 display: flex;
111 flex-direction: column;
112 margin: var(--spacing-4) var(--spacing-4) var(--spacing-8);
113 width: 100%;
114 }
115
116 @media (min-width: 768px) {
117 :global(h1) {
118 font-size: var(--font-size-7);
119 }
120
121 .content {
122 margin: var(--spacing-8) var(--spacing-20) var(--spacing-12);
123 }
124 }
125</style>

😕 SvelteKit FAQ Page SEO: Question Component

Svelte (like Astro) lets us directly add elements to the HTML head section without the need for something like React Helmet. You will see again that the code ends up being quite lightweight. Create a src/lib/components folder and add a Question.svelte file with the following content:

src/lib/components/Question.svelte
svelte
1<script>
2 export let question;
3 export let answer;
4 export let position;
5 export let id;
6 export let url;
7 export let language = 'en-GB';
8
9 const schemaOrgQuestionObject = {
10 '@context': 'https://schema.org',
11 '@type': 'Question',
12 '@id': `${url}#${id}`,
13 position,
14 url: `${url}#${id}`,
15 name: question,
16 answerCount: 1,
17 acceptedAnswer: {
18 '@type': 'Answer',
19 text: answer,
20 inLanguage: language,
21 },
22 inLanguage: language,
23 };
24 let jsonLdString = JSON.stringify(schemaOrgQuestionObject);
25 let jsonLdScript = `
26 <script type="application/ld+json">
27 ${jsonLdString}
28 ${'<'}/script>
29 `;
30</script>
31
32<svelte:head>
33 {@html jsonLdScript}
34</svelte:head>
35
36<section class="container">
37 <details {id} class="question">
38 <summary class="summary">{question}</summary>
39 <div class="answer">
40 <p>
41 {answer}
42 </p>
43 </div>
44 </details>
45</section>

In lines 929, we construct the JSON-LD metadata object. This converts our questions and answers into a form which Google and other search engines can easily interpret. It follows the Schema.org Question structured data pattern. We build up a JSON object and then place it into a script tag in lines 2628. The code in line 28 is just a workaround to ensure our script tag is created as intended.

In Svelte to add something to the HTML head section, we just wrap it in a svelte:head tag. You can see this in lines 3234. Since we have oven-ready HTML we use the @html directive. You will see when we add a simple title meta as plaintext, later, this is not needed. The figure below shows how your finished meta will look in dev tools.

SvelteKit FAQ Page SEO: Dev Tools: Screenshot shows browser window wiht Dev Tools covering the bottom half.  We can see part of the HTML head section.  Shown is a snippet: <script type="application/ld+json">
			{"@context":"https://schema.org","@type":"Question","@id":"https://sveltekit-faq-page-seo.rodneylab.com/#question-3","position":3,"url":"https://sveltekit-faq-page-seo.rodneylab.com/#question-3","name":"Does SvelteKit use vite?","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"Yes. vite, like snowpack is a next generation bundler, building on advances earlier made by more established tools like WebPack.  Among the advantages are faster hot module reloading and better tree shaking.  These benefits come from using ES Modules.","inLanguage":"en-GB"},"inLanguage":"en-GB"}
		</script>
SvelteKit FAQ Page SEO: Dev Tools

Although we add the meta markup to the question component here, you may want to refactor so that all the SEO markup is included in a single script tag for each page. This will depend on the scale and complexity of your site. Keen to hear your philosophy on the ideal structure for different use cases.

If you want the page to look prettier, add some optional styling:

src/lib/components/Question.svelteclick to expand code.
src/lib/components/Question.svelte
svelte
47<style>
48 .container {
49 display: flex;
50 background-image: linear-gradient(
51 to top left,
52 hsl(var(--colour-brand-hue) var(--colour-brand-saturation) var(--colour-brand-luminance)),
53 hsl(
54 var(--colour-brand-hue) var(--colour-brand-saturation)
55 calc(var(--colour-brand-luminance) * 0.95)
56 )
57 );
58 border-radius: var(--spacing-1);
59 margin: var(--spacing-6) auto;
60 width: 100%;
61 }
62
63 .summary {
64 padding: var(--spacing-4);
65 cursor: pointer;
66 font-weight: var(--font-weight-medium);
67 font-size: var(--mobile-font-size-2);
68 }
69
70 .question {
71 display: flex;
72 width: 100%;
73 }
74
75 .answer {
76 background-image: linear-gradient(
77 to bottom right,
78 hsl(var(--colour-mid-hue) var(--colour-mid-saturation) var(--colour-mid-luminance)),
79 hsl(
80 var(--colour-mid-hue) var(--colour-mid-saturation) calc(var(--colour-mid-luminance) * 0.8)
81 )
82 );
83 border: solid var(--spacing-px)
84 hsl(var(--colour-alt-hue) var(--colour-alt-saturation) var(--colour-alt-luminance));
85 border-radius: var(--spacing-px-2);
86 margin: var(--spacing-0) var(--spacing-4) var(--spacing-6);
87 padding: var(--spacing-0) var(--spacing-4);
88 line-height: var(--line-height-relaxed);
89 }
90
91 @media (min-width: 768px) {
92 .summary {
93 font-size: var(--font-size-2);
94 }
95 }
96</style>

🧩 SvelteKit FAQ Page SEO: SEO Component

src/lib/components/SEO.svelte
svelte
1<script>
2 export let datePublished = process.env.VITE_BUILD_TIME;
3 export let dateModified = process.env.VITE_BUILD_TIME;
4 export let seoMetaDescription;
5 export let url;
6 export let language = 'en-GB';
7 export let faqCount;
8 export let title;
9
10 const schemaOrgWebPage = {
11 '@type': ['WebPage', ...(faqCount > 0 ? ['FAQPage'] : [])],
12 '@id': `${url}#webpage`,
13 url,
14 name: title,
15 isPartOf: {
16 '@id': `${url}/#website`,
17 },
18 primaryImageOfPage: {
19 '@id': `${url}#primaryimage`,
20 },
21 ...(faqCount > 0
22 ? {
23 mainEntity: Array.from({ length: faqCount }, (_, index) => index + 1).map((element) => ({
24 '@id': `${url}#question-${element}`,
25 })),
26 }
27 : {}),
28 datePublished,
29 dateModified,
30 description: seoMetaDescription,
31 inLanguage: language,
32 potentialAction: [
33 {
34 '@type': 'ReadAction',
35 target: [url],
36 },
37 ],
38 };
39 const schemaOrgArray = [schemaOrgWebPage];
40 const schemaOrgObject = {
41 '@context': 'https://schema.org',
42 '@graph': schemaOrgArray,
43 };
44 let jsonLdString = JSON.stringify(schemaOrgObject);
45 let jsonLdScript = `
46 <script type="application/ld+json">
47 ${jsonLdString}
48 ${'<'}/script>
49 `;
50</script>
51
52<svelte:head>
53 <title>{title}</title>
54 <html lang="en-GB" />
55 <meta name="description" content={seoMetaDescription} />
56 {@html jsonLdScript}
57</svelte:head>

It is important that you include the FAQPage type here (line 11) for Google to recognise it as an FAQ page. The code in lines 2127 is also essential to this end. We won't look at rest in detail, so the post doesn't get too long. Open up the other SEO posts mentioned earlier for more details and explanation of what we have here.

That was the last component which we needed to add. Let's do some testing next.

🗳️ Poll

Have you looked at the other SEO posts on the site?
Voting reveals latest results.

💯 SvelteKit FAQ Page SEO: Testing

Everything should be working now. You can see the JSON LD markup for your questions if you open up your browser dev tools and go to Inspector, then expand the head section. To see the data clearer right click on a script tag (containing application/ld+json) and select Copy / Inner HTML. This should copy just the JSON, so you can paste it into your code editor and format it to take it easy to read.

Next, deploy a test site to your favourite hosting service then crack open Google's Rich Results Test . Paste in your site's link and check Google has spotted the FAQ meta. If there are issues, Google can be quite pedantic with this particular Schema.org type so check line by line that the meta code we added in both the Question and SEO components matches.

SvelteKit FAQ Page SEO: Google Rich Results Test

🙌🏽 SvelteKit FAQ Page SEO: What we Learned

In this post we looked at:

  • why you would want to add Schema.org FAQ data to your FAQ page,

  • how simple and lightweight the Svelte code for an FAQ page can be,

  • adding and testing Schema.org FAQ data to your SvelteKit FAQ page.

I do hope you can rip out this code and graft it into your own projects. There is a SvelteKit FAQ Page SEO Demo Page at sveltekit-faq-page-seo.rodneylab.com/ . As well as this, you can see the full completed code for this tutorial on the Rodney Lab Git Hub repo .

🏁 SvelteKit FAQ Page SEO: Summary

Why add SEO metadata to your FAQ page

Adding FAQ Schema.org meta to your FAQ page will get it pushed up the search rankings. Key for keeping it there is user interaction. FAQs appear larger in search results as featured snippets and People also ask blocks. Including the markup helps get your page featured. Naturally this is no substitution for good SEO including keyword research and acing other technical SEO aspects.

How do you get your site in a Google featured snippet?

To get your site in a Google featured snippet, the basics are more important. Your content has to be quality and engaging, covering topics Google users are interested in. On top you should include some of the Schema.org meta we talked about in this post. Using SvelteKit or Astro makes it easy to add this extra data to your page.

Is Svelte SEO friendly?

Svelte is considered SEO friendly because it is so easy to add SEO markup to your pages. There is no need for extra dependencies; it all comes for free with built in functionality. Naturally user experience is important for SEO. Svelte has your back here too. Svelte makes it easy to build accessible and fast pages. On top you can create static or server side rendered pages with SvelteKit. If you want partial hydration, Astro is a great choice.

🙏🏽 SvelteKit FAQ Page SEO: Feedback

Have you found the post useful? Would you prefer to see posts on another topic instead? Get in touch with ideas for new posts. Also if you like my writing style, get in touch if I can write some posts for your company site on a consultancy basis. Read on to find ways to get in touch, further below. If you want to support posts similar to this one and can spare a few dollars, euros or pounds, please consider supporting me through Buy me a Coffee.

Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on Twitter and also askRodney on Telegram . Also, see further ways to get in touch with Rodney Lab. I post regularly on SvelteKit as well as other topics. Also subscribe to the newsletter to keep up-to-date with our latest projects.