Nuxt and server rendering
With server-side rendering, the server sends ready HTML, so the page shows fast and search engines can read it. Then Vue hydrates it in the browser. Fetch data with useFetch so it is not fetched twice, keep the first render the same on server and client, never keep user data in module state on the server, and choose a rendering mode per route with routeRules.
Author: bezzad
Contents
The problem: product pages nobody finds
Our shop is a Vue single-page app. The server sends an almost empty HTML file, and the browser builds the page with JavaScript. The team sees three problems:
- On a slow phone, product pages are white for 3 seconds before anything shows.
- Product pages rarely show up well in search results or in link previews, because the HTML has no product name and no price.
- The marketing team wants the home page and the blog to be as fast as a static site.
Server rendering fixes these. Nuxt is the main Vue framework for it.
SSR and hydration
- Server-side rendering (SSR): for each request, the server runs your Vue components and sends the HTML.
- The browser shows that HTML at once. The user sees the product, and search engines and link previews can read it.
- Then the JavaScript loads. Vue hydrates the page: it walks the HTML that is already there, connects it to the components and adds the event listeners. It does not build the DOM again.
- Between “visible” and “hydrated”, buttons do not work yet. A big JavaScript bundle makes this gap long, so SSR does not remove the need for small bundles.
- Code in
<script setup>runs on the server and again in the browser. onMounted runs only in the browser.
Fetch data once: useFetch and useAsyncData
<!-- pages/products/[id].vue -->
<script setup lang="ts">
const route = useRoute();
const { data: product, error } = await useFetch(
() => `/api/products/${route.params.id}`,
);
if (error.value) {
throw createError({ statusCode: 404, statusMessage: 'Product not found' });
}
</script>
- useFetch runs on the server, then sends the result inside the HTML as a payload. In the browser, it reads the payload and does not call the API again.
- A plain
await $fetch()in setup calls the API twice: once on the server, once in the browser. It is also not deduplicated. - Use $fetch in event handlers, like “Add to cart” on click. There is no hydration there.
- useAsyncData does the same for any async function, for example when you call two APIs or an SDK. Give it a unique key.
- The URL is a function, so when the id param changes, useFetch fetches again.
- createError with 404 sends a real 404 status. Search engines then do not index an empty “not found” page as a product.
Hydration mismatch: server and browser must agree
The first render in the browser must make the same HTML as the server. If not, Vue warns about a hydration mismatch and fixes the DOM, which can make the page jump or show wrong text.
<script setup lang="ts">
// Different on server and browser:
const now = new Date().toLocaleTimeString();
const isWide = window.innerWidth > 800; // window is not on the server
</script>
Common causes and fixes:
- Time, random numbers, time zone and locale. The server is in another time zone. Make the value once on the server and send it, or format it only in the browser.
- Browser-only APIs like window, localStorage, or the screen size. Read them in onMounted, or wrap that part in
<ClientOnly>. - User-specific data (like cart count from localStorage). Read it after mount, or put it in a cookie so the server knows it too (useCookie).
- Wrong HTML, like a
<div>inside a<p>. The browser changes the HTML and it no longer matches.
Never share user data in module state on the server
In a single-page app, every user has their own browser. On the server, one Node process serves many users. A ref at the top level of a module is shared by all requests.
// composables/useCart.ts
const items = ref<CartItem[]>([]); // BAD on the server: shared by everyone
export function useCart() {
return { items };
}
User A adds a phone; user B opens the page and sees A’s phone. This is called cross-request state pollution, and it is a privacy bug.
export function useCart() {
const items = useState<CartItem[]>('cart', () => []); // per request
return { items };
}
- useState in Nuxt makes state per request on the server, and sends it to the browser in the payload.
- Pinia in Nuxt (with the @pinia/nuxt module) also creates a new store set per request.
- Only data that is truly the same for everyone (like settings) can be module state, and it must not change per user.
Choose a rendering mode per route
Not every page needs the same mode. Nuxt lets you choose per route with routeRules.
// nuxt.config.ts
export default defineNuxtConfig({
routeRules: {
'/': { prerender: true }, // built once at build time
'/blog/**': { isr: 3600 }, // cached, rebuilt at most once an hour
'/products/**': { swr: 600 }, // SSR, cached 10 minutes
'/account/**': { ssr: false }, // browser only, private data
},
});
- Prerender (SSG): the HTML is made once at build time. Fastest, but the content is as old as the last build.
- ISR / SWR: server-rendered, then cached. The next users get the cached HTML while a new copy is made in the background. ISR needs a host that supports it (like Vercel or Netlify).
- SSR on every request: always fresh, but every request costs server time.
- ssr: false: a normal single-page app for that part. Good for pages behind login, where search engines do not matter.
- Never cache pages with private data in a shared cache. One user would see another user’s data.
Common mistakes
| Mistake | Result | Better way |
|---|---|---|
await $fetch() in setup |
The API is called twice. | useFetch or useAsyncData. |
| Date or window in the first render | Hydration mismatch, page jumps. | Make it on the server once, or onMounted / ClientOnly. |
| Module-level ref with user data | One user sees another user’s cart. | useState or Pinia. |
| Not found page with status 200 | Empty pages in search results. | createError with statusCode 404. |
| SSR for every page | High server cost. | routeRules: prerender, cache, or ssr false. |
| Private pages in a shared cache | Data leak between users. | No shared cache for private pages. |
Summary in 6 lines
- SSR sends ready HTML: fast first view and readable for search engines. Hydration makes it interactive.
- setup runs on the server and in the browser; onMounted runs only in the browser.
- Fetch page data with useFetch or useAsyncData, so it is fetched once and sent in the payload.
- The first browser render must match the server HTML: no time, random or window in it.
- Never keep user data in module state on the server. Use useState or Pinia.
- Choose the mode per route with routeRules: prerender, cache, SSR, or browser only.