SPA fallback for Static Sites

Debbie O'Brien - Apr 13 '20 - - Dev Community

As you know in Nuxt.js you can work with static sites with very little configuration. If you already have a Single Page application and you want to convert it to a static site all you have to do is change the mode from 'spa' to 'universal' in your nuxt.config.js file. If you are already running a universal app then you won't need to modify this.

mode: 'universal'
Enter fullscreen mode Exit fullscreen mode

Then all you have to do is change your build command in Netlify or Azure or wherever your site is being hosted. Instead of using the 'build' command you use the 'generate' command. And that's it. Now your site is a static site.

yarn generate
Enter fullscreen mode Exit fullscreen mode

Everything will be rendered during the build phase which means no need for a server so you can deploy your site for free to Netlify or other static hosting services. And you will have great SEO as everything has already been generated as opposed to a SPA which is generated on client side when the app is launched.

There are also many other benefits of creating static sites such as performance and security.

But what happens when you want to add things to your static site such as a login area or a booking engine. How do we deal with these scenarios? This is where SPA fallback comes into use with the exclude option. Exclude accepts an array of regular expressions and will prevent the generation of these routes however thanks to SPA fallback when set to 'true' they will still be accessible.

Exclude all routes with the word booking:

export default {
  generate: {
    fallback: true,
    exclude: [/^(?=.*\booking\b).*$/]
  }
}
Enter fullscreen mode Exit fullscreen mode

Exclude all routes starting with the word admin:

export default {
  generate: {
    fallback: true,
    exclude: [/^\/admin/]
  }
}
Enter fullscreen mode Exit fullscreen mode

We can also just exclude a complete folder:

export default {
  generate: {
    fallback: true
    exclude: [/booking/, /admin/]
  }
}
Enter fullscreen mode Exit fullscreen mode

We can now basically have a single page application inside our static site. Very cool indeed.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player