Master Server‑Side Rendering with Nuxt.js: A Quick Start Guide
Learn how Nuxt.js extends Vue.js to provide seamless server‑side rendering, from installation and project scaffolding to directory structure, rendering flow, middleware, asyncData handling, routing conventions, and configuration tips, enabling SEO‑friendly, high‑performance web applications.
Vue.js is one of the hottest frontend frameworks, and Nuxt.js is a server‑side rendering framework for Vue.js, offering highly customizable configuration and a simple API that lets developers quickly build SSR projects.
Server‑Side Rendering
Server‑Side Rendering (SSR) is not a new concept; before single‑page applications (SPA) became popular, pages were rendered on the server and sent to the browser. When a user navigates to a new page, the browser requests the server again for a fresh HTML document.
To improve user experience, developers began rendering on the client with JavaScript, separating front‑end and back‑end concerns. Frameworks such as jQuery, React.js, Vue.js, and Angular.js emerged to simplify this process.
While these frameworks bring great convenience, sites that rely heavily on SEO—such as forums, news portals, or corporate homepages—cannot be fully satisfied by client‑side rendering. If search engines cannot index the content, the site’s value diminishes, making SSR essential.
Vue.js provides vue-server-renderer for SSR, but it requires extra work and offers a sub‑optimal developer experience. Nuxt.js solves these problems by handling the heavy lifting automatically.
What Is Nuxt.js?
Nuxt.js is a universal application framework based on Vue.js. It pre‑configures everything needed for SSR and can generate static sites with a single command. Its hot‑reloading mechanism makes development extremely convenient.
First released on October 25, 2016, Nuxt.js quickly gained popularity. The latest stable version at the time of writing is 0.10.7, with version 1.0 still in beta and documentation available in Chinese.
Getting Started Quickly
Using the Vue CLI, you can scaffold a Vue project from a template. Nuxt.js provides its own starter template. After installing the Vue CLI, run: vue init nuxt/starter <projectName> Then install dependencies and start the development server:
npm install
npm run devNuxt.js runs on port 3000. Open http://localhost:3000 in a browser to see the default page with the Nuxt.js logo.
Project Directory Structure
After creating a simple "Hello World" project, the Nuxt.js directory layout looks like this:
Key folders include: .nuxt/: Core library files such as server.js (SSR logic) and router.js (auto‑generated routes). assets/: Static assets processed by Webpack. components/: Vue components (only files in this folder are recognized as components). layouts/: Custom page layouts; include <nuxt /> to render page content. middleware/: Custom middleware executed before loading components. pages/: Files here automatically generate Vue‑Router routes. plugins/: Plugins that run before the root Vue instance is created (e.g., analytics). static/: Assets not processed by Webpack, served from the root (e.g., robots.txt). store/: Vuex state tree. nuxt.config.js: Main configuration file.
Nuxt.js Rendering Process
Nuxt.js performs SSR through several steps:
Invoke nuxtServerInit to preload server‑side data (e.g., logged‑in user info) and await any asynchronous operations.
Enter the Middleware layer, which:
Reads global middleware defined in nuxt.config.js and executes it.
Matches and loads the appropriate layout.
Runs middleware for both the layout and the page.
Call the validate method to verify route parameters or pre‑fetched data; a failure results in a 404 page.
Execute fetch and asyncData. asyncData initializes component data asynchronously, while fetch typically updates the Vuex store.
In the Nuxt source ( util.js) you can find the helper that merges the result of asyncData into the component’s original data method:
export function applyAsyncData (Component, asyncData = {}) {
const ComponentData = Component.options.data || noopData
Component.options.data = function () {
const data = ComponentData.call(this)
return { ...data, ...asyncData }
}
if (Component._Ctor && Component._Ctor.options) {
Component._Ctor.options.data = Component.options.data
}
}After these steps, Nuxt renders the component tree. The overall flow is illustrated below:
Within the .nuxt folder you can find server.js, which encapsulates the SSR logic using a chain of Promise calls.
Nuxt.js Tips and Tricks
Configuring nuxt.config.js
The nuxt.config.js file controls many aspects of a Nuxt project. Below are common configuration sections:
head : Global head settings such as page title, meta tags, and external CSS/JS.
head: {
title: 'My Site',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ name: 'applicable-device', content: 'pc,mobile' }
],
link: [
{ rel: 'stylesheet', href: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' }
],
script: [
{ src: 'https://code.jquery.com/jquery-3.1.1.min.js' },
{ src: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js' }
]
},build : Webpack build rules, vendor modules (e.g., axios), loaders for CSS, images, fonts, etc.
build: {
vendor: ['core-js', 'axios'],
loaders: [
{ test: /\.(scss|sass)$/, use: ['style-loader', 'css-loader', 'sass-loader'] },
{ test: /\.(png|jpe?g|gif|svg)$/, loader: 'url-loader', query: { limit: 1000, name: 'img/[name].[hash:7].[ext]' } },
{ test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url-loader', query: { limit: 1000, name: 'fonts/[name].[hash:7].[ext]' } }
]
},css : Global CSS files automatically injected into every page.
router : Custom routing rules and middleware (e.g., a middleware that reads the User‑Agent header).
loading : Customize the built‑in loading indicator or replace it with a custom component.
env : Define environment variables shared between server and client.
Directory‑Based Routing
Nuxt builds routes automatically from the pages directory. For example, a simple structure creates a base route and two dynamic routes:
The generated route table (found in .nuxt/router.js) looks like:
routes: [
{ path: '/', component: _abe13a78, name: 'index' },
{ path: '/article/:id?', component: _48f202f2, name: 'article-id' },
{ path: '/:page', component: _5ccbb43a, name: 'page' }
]Dynamic routes with optional parameters use the :id? syntax; making the parameter required simply removes the question mark and adds an index.vue file inside the corresponding folder.
When a folder and a file share the same name, Nuxt creates nested routes. In such cases you need to place a <nuxt-child /> component in the parent layout to render child views.
routes: [
{ path: '/article', component: _f930b330, children: [
{ path: '', component: _1430822a, name: 'article' },
{ path: ':id', component: _339e8013, name: 'article-id' }
] }
]Further details on dynamic nested routes are available in the official Nuxt documentation.
Conclusion
Although Nuxt.js is a relatively young framework with room for improvement, it dramatically simplifies building SSR applications for Vue developers. The upcoming 1.0 release is expected to bring even more powerful features.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Baixing.com Technical Team
A collection of the Baixing.com tech team's insights and learnings, featuring one weekly technical article worth following.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
