Go back to blogs

Svelte: change API URLs during Development and Build


Nov 24 '20

This is a frequent question that is asked how to detect whether the environment is either development or production also this is significantly helpful when apps are being frequently published and the client-side app needs API that may be different URL for local/development and during production builds.


Svelte's most adopted bundler is Rollup and the default rollup plugin config looks like this

    plugins: [
            dev: !production,
            css: css => {
            preprocess: sveltePreprocess(),
            browser: true,
            dedupe: ['svelte']
            sourceMap: !production,
            inlineSources: !production
        !production && serve(),
        !production && livereload('public'),
        production && terser()
Enter fullscreen mode Exit fullscreen mode
I have stripped out the comments

We need to add @rollup/plugin-replace as a dev dependency.

npm i -D @rollup/plugin-replace
Enter fullscreen mode Exit fullscreen mode

General usage and more info check out the github

Now, this plugin is going to look for occurrence(s) of MYURL and destructively replace it. So consider having an unique string to be replaced.

For easier explanation here is a quick example.

import replace from 'rollup-plugin-replace';

export default {
    // ...
    plugins: [
Enter fullscreen mode Exit fullscreen mode

Example App.svelte

  let url = "MYURL";
  let api = "/myendpoint";
  url += api;

//your normal fetch logic.

/* async function fetchData() {
        const response = await fetch(url)
        result = await response.json()
        return result

check URL using your template to verify 
when your svelte app is run in dev mode your URL will be http://localhost:3000/myendpoint
when your svelte app is served after the build (production) your URL will be http://myhost:3000/myendpoint

<p> {url} <p> 

<!-- template logic
{#await fetchData()}

Enter fullscreen mode Exit fullscreen mode

Advantage of letting rollup replace the URLs.

Good news, we are not exposing the dev and prod API endpoints on the client-side app. We are leveraging the capabilities of rollup during the build process this makes sure that you not only have the URLs securely in your .env and has only one file you need to change the base URLs. Take a look here how to identify dev or prod the article also achieves using rollup-plugin-replace


  • Paweł Kowalski

    Nice :)
    That is one of those things that you just need to know if you are serious :)

    Do you found a method of pulling dynamically url to CDN during runtime? Similar to webpack-require-from?

    • Shriji

      Ah, this is very neat. Thank you for pointing me this and reading my article :)

      For the answer, if there is a method to dynamically pull URL can be handled by async-script-loader using a small logic. But this isn't a clear equivalent of webpack-require-from.