Server-side rendering (SSR), is the ability of an application to contribute by displaying the web-page on the server instead of rendering it in the browser. Server-side sends a fully rendered page to the client; the client’s JavaScript bundle takes over which then allows the Vue.js app to hydrate.

Node.js server required

A JavaScript environment is required to render your web page.

A Node.js server needs to be configured to execute your Vue.js application.

Extend and control the server

You can extend the server with serverMiddleware and control routes with middleware.

server-middleware/logger.js

  1. export default function (req, res, next) {
  2. console.log(req.url)
  3. next()
  4. }

nuxt.config.js

  1. export default {
  2. serverMiddleware: ['~/server-middleware/logger']
  3. }

If your server middleware consists of a list of functions mapped to paths:

Server vs Browser environments

Because you are in a Node.js environment you have access to Node.js objects such as req and res. You do not have access to the window or document objects as they belong to the browser environment. You can however use window or document by using the beforeMount or mounted hooks.

  1. beforeMount () {
  2. window.alert('hello');
  3. }
  4. mounted () {
  5. window.alert('hello');
  6. }

Server-side rendering steps with Nuxt.js

Step 1: Browser to Server

When a browser sends the initial request, it will hit the Node.js internal server. Nuxt.js will generate the HTML and send it back to the browser with results from executed functions, e.g. asyncData, nuxtServerInit or fetch. Hooks functions are executed as well.

Step 2: Server to Browser

The browser receives the rendered page from the server with the generated HTML. The content is displayed and the Vue.js hydration kicks in, making it reactive. After this process, the page is interactive.

Step 3: Browser to Browser

Navigating between pages with <NuxtLink> is done on the client side so you don’t hit the server again unless you hard refresh the browser.

Caveats

window or document undefined

This is due to the server-side rendering. If you need to specify that you want to import a resource only on the client-side, you need to use the process.client variable.

For example, in your .vue file:

  1. if (process.client) {
  2. require('external_library')
  3. }

iOS and phone numbers

Some mobile Safari versions will automatically transform phone numbers into links. This will trigger a NodeMismatch warning as the SSR content doesn’t match the website content anymore. This can make your app unusable on these Safari versions.

If you include telephone numbers in your Nuxt page, you have two options.

Use a meta tag to stop the transformation

  1. <meta name="format-detection" content="telephone=no" />

Wrap your phone numbers in links

  1. <!-- Example phone number: +7 (982) 536-50-77 -->
  2. <template>
  3. <a href="tel: +7 (982) 536-50-77">+7 (982) 536-50-77</a>
  4. </template>