Opens an external site in a new window
Mental Health Awareness Month
“Community”
RODNEY LAB
  • Home
  • Plus +
  • Newsletter
  • Links
  • Profile
RODNEY LAB
  • Home
  • Plus +
  • Newsletter
  • Links

SvelteKit Static Site HTTP Headers # SvelteKit Static Site HTTP Headers #

blurry low resolution placeholder image SvelteKit Static Site HTTP Headers
  1. Home Rodney Lab Home
  2. Blog Posts Rodney Lab Blog Posts
  3. SvelteKit SvelteKit Blog Posts
<PREVIOUS POST
NEXT POST >
LATEST POST >>

SvelteKit Static Site HTTP Headers #

Published: 4 years ago
5 minute read
Gunning Fog Index: 6.8
2 comments
Content by Rodney
blurry low resolution placeholder image Author Image: Rodney from Rodney Lab
SHARE:

✨ What is a Static Site? #

In this post, we look at how to set up SvelteKit static site HTTP headers. SvelteKit, similarly to tools like Next.js, lets you generate static as well as Server Side Rendered (SSR) sites. SSR is not to be confused with a static site generator (SSG) which is a tool for generating static pages. Static just means that the page is built once for all visitors (rather than custom-built for every visitor) and is typically the same for every user. An example is a typical blog or news site. A site like Twitter however needs to show different content based on who logged in — tweets from the people you follow, messages from your contacts and so on. Typically, since the content is different for every user, a static build will not suit this case.

You can create static sites in SvelteKit using the static adapter. Using that adapter, you can deploy your site to Cloudflare Pages , Netlify and Render among other hosting providers.

We will first have a look at the uses for custom static headers, then have a quick run through the differences between setting SvelteKit static site HTTP headers for static sites and SSR sites. Finally, we will look at how you might go about adding custom HTTP headers to your static SvelteKit site. If that sounds appealing, let's read on!

😕 What do HTTP Headers do? #

HTTP headers are sent along with the body   as part of the server response when you visit a website. The body contains the content you see, while the headers contain metadata. These are different to the HTML head section, which is included in the response body. As an example, cookies are often sent in HTTP header responses from servers. Another example are the dreaded CORS Access Control headers! On your static site you might want to set custom HTTP headers to instruct search engine crawlers or bots not to crawl your site. On top, you can use them to boost your site’s security.

Here's an example of an HTTP header instructing a bot not to index a page:

    
X-Robots-Tag: noindex

The HTTP headers are sent with a response from each page, and can be customized on a per-page basis. This would be useful if you had some pages you were happy for search engines to index, while not wanting them to index others.

🗳 Poll #

How are you implementing partial hydration on new projects?
Voting reveals latest results.

🔌 Using the SvelteKit Static Adapter #

Just like there are SvelteKit adapters for building SSR sites to run on Cloudflare Workers, Netlify, Node-based environments and Render, there is an adapter for building static sites. Note, you can use the same SvelteKit static adapter for all the hosts  mentioned above. There is not too much to configuring it. First, download the next version of the static the adapter into your project:

    
pnpm i -D @sveltejs/adapter-static@next

Then update your svelte.config.js file to use the adapter:

svelte.config.js
javascript
    
1 /** @type {import('@sveltejs/kit').Config} */
2 import adapter from '@sveltejs/adapter-static';
3
4 const config = {
5 kit: {
6 adapter: adapter(),
7 // hydrate the <div id="svelte"> element in src/app.html
8 target: '#svelte'
9 }
10 };
11
12 export default config

Note, you can also go for the half-in-half-out option, where you make only some pages static. In this case, you use the SSR adapter for your platform, then add this line to the load function in the Svelte file for any pages you want to static render:

    
1 <script context="module">
2 export const prerender = true;
3 // TRUNCATED...
4 </script>

⚖️ How is Adding Custom HTTP Headers different for Static Sites? #

With server side rendered sites, you can use the src/hooks.js file to add any headers you want to the HTTP responses. As an example, you can take a peek at the SvelteKit MDsveX Starter .

Because your node server, Lambda Function or Cloudflare worker which provides server side content sends the headers, you can update headers from the hooks.js file. With a static site, it is the Cloudflare, Netlify, or Render servers which respond directly to HTTP requests. That does not mean you cannot add custom headers, though! Typically, you add a _headers file to your build directory, and you’re away (with Render you update the headers in the Dashboard). We'll look at this next.

⚙️ Adding Custom HTTP Headers to your Static SvelteKit Site #

In the previous section, we saw you need to add a _headers file to your SvelteKit build directory. This will work with Cloudflare Pages and Netlify. By default, your build directory will be /build in the root directory of your project.

Probably the easiest way to create the _headers file is to write a short script that generates it and update your package.json file's build script to run that script. This way, your host will generate the file automatically when you run builds.

To do this, first update your package.json file:

package.json
json
    
1 {
2 "name": "sveltekit-blog-mdx",
3 "version": "1.0.0",
4 "scripts": {
5 "dev": "svelte-kit dev --port 3000",
6 "build": "svelte-kit build && node ./generate-headers",
7 "preview": "svelte-kit preview --port 3000",
8 "generate:headers": "node ./generate-headers.js",
9 },
10 // ...
11 }

Then create a script which adds the headers you want in a generate-headers.js file in the root directory of your project:

generate-headers.js
javascript
    
1 import fs from 'fs';
2 import path from 'path';
3
4 const __dirname = path.resolve();
5 const buildDir = path.join(__dirname, 'build');
6
7 function main() {
8 const headers = `/*
9 X-Frame-Options: DENY
10 X-XSS-Protection: 1; mode=block
11 X-Content-Type-Options: nosniff
12 Referrer-Policy: same-origin
13 Permissions-Policy: accelerometer=(), autoplay=(), camera=(), document-domain=(), encrypted-media=(), fullscreen=(), gyroscope=(), interest-cohort=(), magnetometer=(), microphone=(), midi=(), payment=(), picture-in-picture=(), publickey-credentials-get=(), sync-xhr=(), usb=(), xr-spatial-tracking=(), geolocation=()
14 Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
15 `;
16
17 const headersFile = path.join(buildDir, '_headers');
18 fs.writeFileSync(headersFile, headers);
19 }
20
21 main();

This is just to give you an idea of what you might want to add. You might consider adding Content Security Policy headers  or making the Permissions Policy headers less restrictive. If your aim is improving security, run a test on securityheaders.com  or see the Mozilla Observatory as an alternative from this list of useful links:

  • Content Security Policy Reference 
  • Observatory: Security Header site scanning from Mozilla 
  • Cloudflare Pages custom headers docs 
  • Netlify docs on syntax for _headersfile 

If you are hosting your static site on Render, you can add headers in the Render dashboard .

🙌🏽 SvelteKit Static Site HTTP Headers: What we Learned #

In this post, we saw:

  • what HTTP headers are;
  • how SSR sites differ from static sites; and
  • a way you might include custom SvelteKit static site HTTP headers in your project.

I do hope there is at least one thing in this article which you can use in your work or a side project. As always, get in touch with feedback if I have missed a trick somewhere!

🙏🏽 SvelteKit Static Site HTTP Headers: Feedback #

Have you found the post useful? Do you have your own methods for solving this problem? Let me know your solution. Would you like 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.

Thanks for reading this post. I hope you found it valuable. Please get in touch with your feedback and suggestions for posts you would like to see. Read more about me …

blurry low resolution placeholder image Rodney from Rodney Lab
TAGS:
SVELTEKIT

Related Posts

blurry low resolution placeholder image SvelteKit Local Edge Functions: Edge on Localhost

SvelteKit Local Edge Functions: Edge on Localhost

sveltekit
deno
<PREVIOUS POST
NEXT POST >
LATEST POST >>

Leave a comment …

Your information will be handled in line with our Privacy Policy .

Comments

  • CT

    "Static just means that the page is built once for all visitors (rather than custom built for every visitor) and is typically the same for every user." Understood, but a "regular" API call could be made from a static page at any time, right? In other words the structure of the page may be consistent for all users, but user-specific data could be loaded from a database, even on a "static" page hosted on a Netlify, without having to rebuild? Thanks for this post!

    4 years ago
    • Rodney

      Hey CT, yep that's right, you can make API calls from static sites Think of static as referring to the HTML. Static pages can include JavaScript and be interactive. Yep you could load user specific content into a div for example, using JavaScript on a static site, but you might be able to get a better user experience with a server side rendered page in this case. SvelteKit lets you make some pages static and others SSR. The capabilities of static and SSR sites are increasingly intersecting and you should continue to push the limits to get the best user experience. Hope that makes sense and thanks for the feedback!
      4 years ago

Ask for more

1 Nov 2022 — Astro Server-Side Rendering: Edge Search Site
3 Oct 2022 — Svelte eCommerce Site: SvelteKit Snipcart Storefront
1 Sept 2022 — Get Started with SvelteKit Headless WordPress

Copyright © 2020 – 2025 Rodney Johnson. All Rights Reserved. Please read important copyright and intellectual property information.

  • Home
  • Profile
  • Plus +
  • Newsletter
  • Contact
  • Links
  • Terms of Use
  • Privacy Policy
We use cookies  to enhance visitors’ experience. Please click the “Options” button to make your choice.  Learn more here.