P

Creating a headless website with Svelte

With SvelteKit it is possible to power the entire website using Pullnote and a handful of files.

1. Create a Svelte project

npm create svelte@latest my-app
cd my-app
npm install
npm run dev

See https://kit.svelte.dev/docs/creating-a-project for more

2. +layout.server.js

Under /src/routes, create a file called +layout.server.js :

// Pull folders and page content from pullnote.com
export async function load({url, params}) {
  var res = await fetch("https://pullnote.com/pull/note" + url.pathname, {
    headers: {
      "Content-Type": "application/json; charset=utf-8",
      "pn_authorization": "Bearer YOUR_API_KEY"
    }
  });
  var note = await res.json();
  return {note}
}

3. /routes/[...slug]

Create a folder called [...slug] under routes and add an empty +page.svelte file to it. This will catch all of the sub-folders and content.

4. +layout.svelte

Drop this +layout.svelte file into /routes

<script>
  export let data;
  // Make the note reactive so that the layout refreshes on url change
  $: note = data.note;
</script>

<svelte:head>
  {@html note.head_html}
</svelte:head>

<a href={data.note.category.pathname}>
  {data.note.category.title}
</a>

<h1>{note.title}</h1>

{#if note.picture}
  <img src={note.img.src} alt={note.img.alt} />
{/if}

{@html note.content_html}

<slot />

{#if note.is_category}
  <hr />
  <ul>
    {#each note.links as link}
      <li>
        <a class="link" href={link.pathname}>
          {link.title}
        </a>
      </li>
    {/each}
  </ul>
{/if}

5. Styling

Tweak app.css or add tailwind to give your site some colour and font love.


Developers Blog T&Cs Privacy