Server Side Rendering with Nuxt Tips

by Joe Marshall on March 4th, 2020

Nuxt is a Vue-based universal application framework - it can be used to create either a series of static pages, a [Server-Side Rendered] (SSR) app, or a traditional SPA.

SSR especially is a great feature since it helps with SEO - (one of the reasons we choose to use it) - and because it can be a little tricky to get right, it's wonderful it comes with so little configuration in Nuxt.

There are however, a few basics for developing a Nuxt app with SSR in mind.

asyncData

asyncData is the SSR workhorse. As outlined in the documentation this method exists only on page components and is called once on the server and then rendered client-side on any subsequent routes.

export default {
    async asyncData({ store, params }) {
    }
}

This is where pretty much all of your data-fetching will go and will give you that nice smooth experience without the flicker of the DOM being re-rendered. Within asyncData you can access the store and params objects and use them to save any information you might grab.

Here's an example of grabbing pricing information from an API endpoint and then returning it as a deconstructed plans object. Any data returned from asyncData is merged into your larger data object.

async asyncData({ store, params }) {
    let plans = await listPlans(store.state.userToken)
    return {plans};
}

process.client, process.server and window

Using these config properties you can do checks to see if you're in the client or server, which is useful if you want to trigger a client-side only library. There's also the option for that case of using the global browser window object to check for / trigger any client-side libraries. For example, a code highlighting plugin.

if (window.Prism) {
    window.Prism.highlightAll()    

<no-ssr/> and <client-only/>

There's also a simple tag you can use (no-ssr if Nuxt is < v2.9.0, client-only otherwise) to also control the less isomorphic app behavior and force a client-side render.

You might use this behavior for something like only rendering a loading icon in the client side and skipping it on the server.

These are just a few of the common staples of Nuxt SSR-oriented development, but hopefully they've covered the basics and given you a couple points to research for your own SSR conversion!

< Back to Blog

Sign up for future posts