How to hide server code from client side in SvelteKit

Do you have secret API keys, environment variables, maybe business logic you want to hide? But you’re not sure how to prevent from SvelteKit importing code to the client-side?

It’s actually really simple! To prevent code from being important to the client-side in SvelteKit, you must use the namespace .server in your file name or add your server code in the $lib/server directory!

Let’s look at each example!

Solution #1: Using .server namespace in your filename

By adding the namespace, .server you’ll prevent from code inside that file to be leaked to the client side. Here is the app structure for this example.


src/
    - lib/
        - secret.server.js
    - routes/
        - +page.svelte

Now let’s look at some secret server code ONLY!


export const echoSecretMessage = () => console.log('Should only print on server!');

Now let’s try to print the secret message into the client-side of +page.svelte.


<script>
    import { echoSecretMessage } from '$lib/secret.server.js';

    console.log(echoSecretMessage())

</script>

When you’re running the app locally, you should 500 internal error message, and your terminal should print a message similar to this:


Cannot import $lib/secret.server.js into client-side code:
- src/routes/+page.svelte 
  - $lib/secret.server.js

Solution #2: Add server code inside $lib/server directory

Another solution to prevent importing code to the client-side in SvelteKit is to move code files into the server directory. Let’s look at a SvelteKit app structure example:


src/
    - lib/
        - server/
            - secret.js
    - routes/
        - +page.svelte

Now let’s update the +page.svelte import.


<script>
    import { echoSecretMessage } from '$lib/server/secret.js';

    console.log(echoSecretMessage())

</script>

You should still get the same error message:


Cannot import $lib/secret.server.js into client-side code:
- src/routes/+page.svelte 
  - $lib/secret.server.js

And in-case the local environment doesn’t catch it, the build will!


Cannot import $lib/server/secret.js into client-side code:
- .svelte-kit/generated/nodes/2.js 
  - src/routes/+page.svelte 
    - $lib/server/secret.js 
error during build:
Error: Cannot import $lib/server/secret.js into client-side code:
- .svelte-kit/generated/node

I like to tweet about Svelte and post helpful code snippets. Follow me there if you would like some too!