Sveltekit Change Page Title Dynamically


The <svelte:head> is a special element you can use to insert elements inside the <head> element of a webpage.
You can add this to any page and set the page name like so:
<svelte:head>
<title>Tutorial</title>
</svelte:head>
pathname)Setting the page name in a static manner can be a repetitive process. We can improve this by using the +layout.svelte file.
Open +layout.svelte & import page from $app/stores
import { page } from "$app/stores";
Console log these values to understand what the page store is holding
$: console.log("page info is: ");
$: console.log($page);
$: console.log($page.params.b);
$: console.log($page.route.id);
$: console.log($page.url.pathname);
Let’s use the $page.url.pathname output
Notice the $page.url.pathname output consists of a ‘/’ at the beginning, to remove that we can use the JavaScript slice(1) function, which will slice and remove the first character
Now add the svelte head
<svelte:head>
<title>Tutorial | {$page?.url?.pathname?.slice(1)}</title>
</svelte:head>
Interpret the code like this - The expression
$page?.url?.pathnamewill first check if$pageis defined. If$pageexists, it then checks if$page.urlis defined. Finally, if both$pageand$page.urlis present, it will access the pathname property of$page.urlIf at any point in this chain, something is
undefinedornull, the entire expression will safely returnundefinedwithout throwing an error, thanks to the optional chaining operator
At this point, the title should look fine, but if you visit your homepage, you will see an extra “ |” after your website name.
Let’s improve the code again
<svelte:head>
<title>
Tutorial {$page?.url?.pathname != '/' ? `|
${$page?.url?.pathname?.slice(1)}` : ''}
</title>
</svelte:head>
Interpret the code like this - if
$page?.url?.pathnamevalue is NOT same as ‘/’ then print the$page?.url?.pathnamevalue and slice the first character, if not then print blank string ‘ ’

Improve caching and performance in SvelteKit by importing images from src/lib instead of static. Learn why and how this approach works.