Using Netlify Functions with SvelteKit
Tags: svelte, webdev, javascript, serverless
Published: 2021-09-13 07:48:25

---
title: "Using Netlify Functions with SvelteKit"
published: "true"
description: "Using Netlify Functions with SvelteKit: learn how you can continue using your existing Netlify functions when you move your site to SvelteKit."
tags: "svelte, webdev, javascript, serverless"
canonical_url: "https://rodneylab.com/using-netlify-functions-sveltekit/"
cover_image: "https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3t6ir6gi2xo93ok2xwco.png"
---
## ☁️ Using Netlify Functions with SvelteKit

Why would you want to be using Netlify Functions with SvelteKit instead of the inbuilt SvelteKit functionality? Like NextJS from the React world SvelteKit supports server side rendering as well as server side routes from which you can run your server side code.  There are a couple of reasons that come to mind for using Netlify functions with SvelteKit though.  Firstly, if you are migrating your site from another platform and have existing Netlify functions, you can speed up the migration by transplanting over the existing Netlify functions.

Another reason for using Netlify functions in your SvelteKit app is to gain access to other languages in your functions.  You can <a aria-label="Read post on writing Netlify functions in Rust" href="https://rodneylab.com/use-serverless-rust-with-netlify-functions/">write Netlify functions in Rust</a> among other languages.  Using API server routes in SvelteKit, you would be limited to JavaScript.  You might choose Rust over JavaScript when performance is critical as typically you can optimise Rust code to run faster than equivalent JavaScript.

The good news is (as we will see in a moment) that besides a couple of configuration files, you don't need much to get your Netlify functions working in tandem with SvelteKit.

## 🧑🏽‍🎓 How to Get Started Using Netlify Functions with SvelteKit

We'll look at these three steps in turn which will get you using Netlify Functions with SvelteKit in no time:

1. `netlify.toml` configuration file,

2. Netlify adapter,

3. create functions.

## ⚙️ <code>netlify.toml</code> Config File

Create a `netlify.toml` file in the root directory of your project and add the following content:

```toml
[build]
  command = "npm run build"
  publish = "build"
 
[dev]
 command = "svelte-kit dev"
 
[functions]
  directory = "netlify/functions"
  node_bundler = "esbuild"
```

Probably the most important part here is specifying the directory where we will put the Netlify functions (`netlify/functions`).


## 🔌 Netlify Adapter

Svelte has build adapters which help customise your site build for your hosting platform.  This is exactly what the <ExternalLink aria-label="Open Netlify Svelte Kit adapter documentation" href="https://github.com/sveltejs/kit/tree/master/packages/adapter-netlify">Netlify adapter does</ExternalLink>.  Part of its work is to convert any server endpoints to Netlify functions.  This means your build app will have a render function (generated by the adapter) as well as any Netlify functions you define yourself.

The SvelteKit adapters are still evolving.  As such, current best practice is to choose the `next` version, which you can install with pnpm, npm or yarn:

```shell
pnpm i -D @sveltejs/adapter-netlify@next
```

On top, you will need to let SvelteKit know that you want it to use this adapter:

```javascript
/** @type {import('@sveltejs/kit').Config} */
import adapter from '@sveltejs/adapter-netlify';
import { imagetools } from 'vite-imagetools';
import { mdsvex } from 'mdsvex';
import preprocess from 'svelte-preprocess';
 
const config = {
  extensions: ['.svelte', '.md', '.svelte.md'],
  preprocess: [
    mdsvex({ extensions: ['.svelte.md', '.md', '.svx'] }),
    preprocess({
      scss: {
        prependData: "@import 'src/lib/styles/variables.scss';",
      },
    }),
  ],
  kit: {
    adapter: adapter(),
    files: {
      hooks: 'src/hooks',
    },
    // hydrate the <div id="svelte"> element in src/app.html
    target: '#svelte',
    vite: {
      define: {
        'process.env.VITE_BUILD_TIME': JSON.stringify(new Date().toISOString()),
      },
      plugins: [imagetools({ force: true })],
    },
  },
};
 
export default config;
```

Import the adapter to your `svelte.config.js` file (line `2`) and then set it as SvelteKit's adapter (line&nbsp;`18`).


## 🖥 The Netlify Functions

Next you can create the `netlify/functions` directory in your project and add any functions there.  You are not limited to JavaScript here.  <Link aria-label="See post on using Rust in Netlify Serverless Functions" to="/use-serverless-rust-with-netlify-functions/">Take a look at the post on using Rust for Netlify functions</Link> to get started with other languages.

Here are a couple of JavaScript test functions you can use to try out your setup.  The first can be used to get a client IP.  You might need this if you are doing spam detection.  The second just returns a JSON object:

```javascript
exports.handler = async (event, _, callback) => {
  const ip = event.headers['x-forwarded-for'];
  const client = ip.split(',')[0];
  callback(null, {
    statusCode: 200,
    body: client,
  });
};
```

```javascript
exports.handler = async function () {
  return {
    statusCode: 200,
    body: JSON.stringify({ message: 'Good morning!' }),
  };
};
```

## 💯 Testing it out

![Using Netlify Functions with SvelteKit: test output for good morning function show stringifed J S O N object in browser. Object has a message field whose value is Good morning!](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uy3wuoqca9193io8zkw2.png)

In the Netlify tradition, configuration and boilerplate are kept to a minimum.  To get these functions running, you should just need to commit these changes to your git repository, and deploy as normal.  To test the `client-ip` function, you need to point your browser to the `/.netlify/functions/client-ip` route (see the working example here: <ExternalLink aria-label="Test the client IP Netlify function" href="https://sveltekit-netlify-functions.rodneylab.com/.netlify/functions/client-ip">sveltekit-netlify-functions.rodneylab.com/.netlify/functions/client-ip</ExternalLink>).  Similarly for the `good-morning` function, point your browser to `/.netlify/functions/good-morning`.  Again, there is a live test site at <a aria-label="Test the client IP Netlify function" href="https://sveltekit-netlify-functions.rodneylab.com/.netlify/functions/good-morning">sveltekit-netlify-functions.rodneylab.com/.netlify/functions/good-morning</a>.

I have also created a <a aria-label="Open the full working repo"  href="https://github.com/rodneylab/sveltekit-netlify-functions">full working repo on the Rodney Lab GitHub page</a>.

## 🙌🏽 Wrapup

In this post we saw:

- why you might want to use Netlify functions with SvelteKit,

- how to configure a Netlify SvelteKit build,

- how to add Netlify functions to your SvelteKit app.

This post came from a question left in a comment.  So if this post spurs further questions, please do drop a comment below and I might be able to create more content in response.

## 🙏🏽 Feedback

Have you found the post useful? Which other hosting service would you like to know how to host a SvelteKit site on? 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 <a aria-label="Support Rodney Lab via Buy me a Coffee" href="https://rodneylab.com/giving/">consider supporting me through Buy me a Coffee</a>.

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 <a aria-label="Message me on Twitter" href="https://twitter.com/messages/compose?recipient_id=1323579817258831875">@askRodney</a> on Twitter and also <a aria-label="Contact Rodney Lab via Telegram" href="https://t.me/askRodney">askRodney on Telegram</a>. Also, see <Link aria-label="Get in touch with Rodney Lab" to="/contact">further ways to get in touch with Rodney Lab</Link>. I post regularly on <a aria-label="See posts on svelte kit" href="https://rodneylab.com/tags/sveltekit/">SvelteKit</a> as well as other topics. Also <a aria-label="Subscribe to the Rodney Lab newsletter" href="https://rodneylab.com/about/#newsletter">subscribe to the newsletter to keep up-to-date</a> with our latest projects.