Home Web Development Hands-on Nuxt.js Web Development

Hands-on Nuxt.js Web Development

By Lau Tiam Kok
books-svg-icon Book
eBook $35.99 $24.99
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $35.99 $24.99
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Introducing Nuxt
About this book
Nuxt.js is a progressive web framework built on top of Vue.js for server-side rendering (SSR). With Nuxt.js and Vue.js, building universal and static-generated applications from scratch is now easier than ever before. This book starts with an introduction to Nuxt.js and its constituents as a universal SSR framework. You'll learn the fundamentals of Nuxt.js and find out how you can integrate it with the latest version of Vue.js. You'll then explore the Nuxt.js directory structure and set up your first Nuxt.js project using pages, views, routing, and Vue components. With the help of practical examples, you'll learn how to connect your Nuxt.js application with the backend API by exploring your Nuxt.js application’s configuration, plugins, modules, middleware, and the Vuex store. The book shows you how you can turn your Nuxt.js application into a universal or static-generated application by working with REST and GraphQL APIs over HTTP requests. Finally, you'll get to grips with security techniques using authorization, package your Nuxt.js application for testing, and deploy it to production. By the end of this web development book, you'll have developed a solid understanding of using Nuxt.js for your projects and be able to build secure, end-to-end tested, and scalable web applications with SSR, data handling, and SEO capabilities.
Publication date:
August 2020
Publisher
Packt
Pages
698
ISBN
9781789952698

 
Introducing Nuxt

Welcome to your journey of Hands-on Nuxt.js Web Development. In this chapter, we will peer inside Nuxt to see what constitutes this framework. We will walk you through Nuxt's features and you will get to know the pros and cons of the different types of applications that Nuxt falls in line with. Last but not least, you will discover the great potential of using Nuxt as a universal SSR app, a static site generator, and a single-page app.

In this chapter, we will cover the following topics:

  • From Vue to Nuxt
  • Why Use Nuxt?
  • Types of applications
  • Nuxt as a universal SSR app
  • Nuxt as a static site generator
  • Nuxt as a single-page app

Let's get started!

 

From Vue to Nuxt

Nuxt is a higher-level Node.js web development framework for creating Vue apps that can be developed and deployed in two different modes: universal (SSR) or single-page application (SPA). Furthermore, you can deploy SSR and SPA in Nuxt as static-generated apps. Even though you can choose the SPA mode, the full power of Nuxt lies in its universal mode or server-side rendering (SSR) for building universal apps. A universal app is used to describe JavaScript code that can execute both on the client and the server-side. But if you wish to develop a classic (or standard/traditional) SPA, which executes on the client-side only, you may want to consider using vanilla Vue.

Note that an SPA mode Nuxt app is slightly different from a classic SPA. You will find out more about it later in this book and briefly in this chapter.

Nuxt is created on top of Vue, supercharged with some extra features such as asynchronous data, middleware, layouts, modules, and plugins that execute your app on the server-side first, and then on the client-side. This means the app generally renders quicker than the traditional server-side (or multiple-page) apps.

Nuxt is pre-installed with the following packages so that you don't have to install them, which you would do in a standard Vue app:

On top of that, Nuxt uses webpack and Babel to compile and bundle your code with the following webpack loaders:

In a nutshell, webpack is a module bundler that bundles all the scripts, styles, assets, and images in your JavaScript app, while Babel is a JavaScript compiler that compiles or transpiles the next-generation JavaScript (ES2015+) to browser-compatible JavaScript (ES5) so that you can run your code on current browsers.

For more information about webpack and Babel, please visit https://webpack.js.org/ and https://babeljs.io/, respectively.

webpack uses what they call loaders to preprocess your files when you import them via the JavaScript import statement or require method. You can write your loaders but you don't have to do so when compiling your code in Vue files since they have been created for you by the Babel community and Vue team. We'll discover the great features that come with Nuxt and those contributed by these loaders in the next section.

 

Why use Nuxt?

Frameworks such as Nuxt exist because of the shortcomings of the traditional SPA and the server-side rendering of multi-page applications (MPAs). We can regard Nuxt as a hybrid of server-side rendering MPA and traditional SPA. Hence, it is dubbed "universal" or "isomorphic". So, being able to do server-side rendering is the defining feature of Nuxt. In this section, we will walk you through other prominent features of Nuxt that will make your app development easy and fun. The first feature we'll look at allows you to write single-file Vue components by using a .vue extension in your files.

Writing single-file components

There are a few methods we can use to create a Vue component. A global Vue component is created by using Vue.component, as follows:

Vue.component('todo-item', {...})

On the other hand, a local Vue component can be created using a plain JavaScript object, as follows:

const TodoItem = {...}

These two methods are manageable and maintainable if you're using Vue for a small project, but it becomes difficult to manage for a big project when you have tons of components with different templates, styles, and JavaScript methods all at once.

Hence, single-file components come to the rescue, in which we only use one .vue file for each Vue component. If you need more than one component in your app, then just separate them into multiple .vue files. In each of them, you can write the template, script, and style that relate to that particular component only, as follows:

// pages/index.vue
<template>
<p>{{ message }}</p>
</template>

<script>
export default {
data () {
return { message: 'Hello World' }
}
}
</script>

<style scoped>
p {
font-size: 2em;
text-align: center;
}
</style>

Here, you can see how we have an HTML template that prints the message from the JavaScript script and the CSS style that describes the presentation of the template, all in one single .vue file. This makes your code more structured, readable, and organizable. Sweet, isn't it? This is only made possible by vue-loader and webpack. In Nuxt, we only write components in .vue files, regardless of whether they are components in the /components/, /pages/, or /layouts/ directory. We will explore this in more detail in Chapter 2, Getting Started with Nuxt. Now, we'll look at the Nuxt feature that allows you to write ES6 JavaScript out of the box.

Writing ES2015+

Nuxt compiles your ES6+ code out of the box without you having to worry about configuring and installing Babel in webpack. This means you can write ES6+ code straight away and your code will be compiled into JavaScript that can be run on older browsers. For example, you will see the following destructuring assignment syntax often when using an asyncData method:

// pages/about.vue
<script>
export default {
async asyncData ({ params, error }) {
//...
}
}
</script>

The destructuring assignment syntax is used in the preceding code to unpack the properties from the Nuxt context into distinct variables that we can use for the logic inside the asyncData method.

For more information about the Nuxt context and ECMAScript 2015 features, please visit https://nuxtjs.org/api/context and https://babeljs.io/docs/en/learn/, respectively.

Writing ES6 in Nuxt is only made possible by babel-loader and webpack. There's more than just the destructuring assignment syntax that you can write in Nuxt, including the async function, the await operator, the arrow function, the import statement, and many more. What about the CSS preprocessor? If you write CSS styles with a popular CSS preprocessor such as Sass, Less, or Stylus, but if you are a Sass person and not a Less person, nor a Stylus person, can Nuxt support any of them? The short answer is yes. We'll find out the long answer to this question in the next section.

Writing CSS with a preprocessor

In Nuxt, you can choose your favorite CSS preprocessor to write the styles for your app, whether it is Sass, Less, or Stylus. They are already pre-configured for you in Nuxt. You can check out their configurations at https://github.com/nuxt/nuxt.js/blob/dev/packages/webpack/src/config/base.js. So, you just need to install the preprocessor and its webpack loader in your Nuxt project. For example, if you want to use Less as your CSS preprocessor, just install the following dependencies in your Nuxt project:

$ npm i less --save-dev
$ npm i less-loader --save-dev

Then, you can start writing your Less code by setting the lang attribute to "less" in the <style> block, as follows:

// pages/index.vue
<template>
<p>Hello World</p>
</template>

<style scoped lang="less">
@align: center;
p {
text-align: @align;
}
</style>

From this example, you can see that writing modern CSS styles is as easy as writing modern JavaScript in Nuxt. All you are required to do is install your favorite CSS preprocessor and its webpack loader. We will use Less in this book in the upcoming chapters, but for now, let's find out what other features Nuxt offers.

For more information about these preprocessors and their webpack loaders, please visit the following links:

Even though PostCSS is not a preprocessor, if you want to use it in a Nuxt project, please visit the guide provided at https://nuxtjs.org/faq/postcss-plugins.

Extending Nuxt with modules and plugins

Nuxt was created on top of a modular architecture. This means you can extend it with endless modules and plugins for your app or Nuxt community. This also means you can choose tons of modules and plugins from the Nuxt and Vue communities so that you don't have to reinvent them for your app. The links to these are as follows:

Modules and plugins are simply JavaScript functions. Don't worry about the distinction between them for now; we will get to this in Chapter 6, Writing Plugins and Modules.

Adding transitions between routes

Unlike traditional Vue apps, in Nuxt, you don't have to use the wrapper <transition> element to handle JavaScript animations, CSS animations, and CSS transitions on your elements or components. For example, if you want to apply a fade transition to the specific page when navigating to it, you can just add the transition name (for example, fade) to the transition property of that page:

// pages/about.vue
<script>
export default {
transition: {
name: 'fade'
}
}
</script>

Then, you can just create the transition style in a .css file:

// assets/transitions.css
.fade-enter,
.fade-leave-to {
opacity: 0;
}

.fade-leave,
.fade-enter-to {
opacity: 1;
}

.fade-enter-active,
.fade-leave-active {
transition: opacity 3s;
}

The "fade" transition will apply to the about page automatically when navigating to the /about route. Cool, isn't it? Don't worry if the code or the class names look a bit overwhelming to you at this point; we will look at this transition feature and explore it in more detail in Chapter 4, Adding Views, Routes, and Transitions.

Managing the <head> element

Also, unlike traditional Vue apps, you can manage the <head> block of your app out of the box without installing the additional Vue package that handles it – vue-meta. You just add the data you need for <title>, <meta>, and <link> via the head property to any page. For example, you can manage the global <head> element via the Nuxt config file of your app:

// nuxt.config.js
export default {
head: {
title: 'My Nuxt App',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'My Nuxt app is
about...' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
}
}

Nuxt will convert this data into the HTML tags for you. Again, we will learn about this feature and explore it in more detail in Chapter 4, Adding Views, Routes, and Transitions.

Bundling and splitting code with webpack

Nuxt uses webpack to bundle, minify, and split your code into chunks that can speed up the load time of your app. For example, in a simple Nuxt app with two pages, index/home and about, you will get similar chunks for the client-side:

Hash: 0e9b10c17829e996ef30 
Version: webpack 4.43.0
Time: 4913ms
Built at: 06/07/2020 21:02:26
Asset Size Chunks Chunk Names
../server/client.manifest.json 7.77 KiB [emitted]
LICENSES 389 bytes [emitted]
app.3d81a84.js 51.2 KiB 0 [emitted] [immutable] app
commons/app.9498a8c.js 155 KiB 1 [emitted] [immutable] commons/app
commons/pages/index.8dfce35.js 13.3 KiB 2 [emitted] [immutable] commons/pages/index
pages/about.c6ca234.js 357 bytes 3 [emitted] [immutable] pages/about
pages/index.f83939d.js 1.21 KiB 4 [emitted] [immutable] pages/index
runtime.3d677ca.js 2.38 KiB 5 [emitted] [immutable] runtime
+ 2 hidden assets
Entrypoint app = runtime.3d677ca.js commons/app.9498a8c.js app.3d81a84.js

The chunks that you would get for the server-side will look as follows:

Hash: 8af8db87175486cd8e06 
Version: webpack 4.43.0
Time: 525ms
Built at: 06/07/2020 21:02:27
Asset Size Chunks Chunk Names
pages/about.js 1.23 KiB 1 [emitted] pages/about
pages/index.js 6.06 KiB 2 [emitted] pages/index
server.js 80.9 KiB 0 [emitted] app
server.manifest.json 291 bytes [emitted]
+ 3 hidden assets
Entrypoint app = server.js server.js.map

These chunks and the build information are generated when you use Nuxt npm run build command to build your app for deployment. We will look at this in more detail in Chapter 14, Using Linters, Formatters, and Deployment Commands.

This aside, there are other great features and plugins from webpack that are used by Nuxt, such as static files and asset serving (asset management), hot module replacement, CSS extraction (extract-css-chunks-webpack-plugin), a progress bar while you're building and watching (webpackbar), and so on. For more information, please visit the following links:

These great features from webpack, Babel, and Nuxt itself will make your modern project development fun and easy. Now, let's take a look at the various application types to see why you should or shouldn't use Nuxt when you're building your next web app.

 

Types of applications

The web applications of today are very different from the ones from decades ago. We had fewer options and solutions in those days. Today, they are blooming. Whether we call them "applications" or "apps", they are the same. We will call them "apps" in this book. So, we can categorize our current web apps as follows:

  • Traditional server-side rendered app
  • Traditional SPA
  • Universal SSR app
  • Static-generated app

Let's go through each of them and understand the pros and cons. We will first look at the oldest type of app the traditional server-side rendered app.

Traditional server-side rendered app

Server-side rendering is the most common approach for delivering the data and HTML to the client side on the browser on your screen. It was the only way to do things when the web industry just started. In traditional server-rendered apps or dynamic websites, every request requires a new page re-rendered from the server to the browser. This means you will reload all the scripts, styles, and template(s) once more with every request you send to the server. The idea of reloading and re-rendering does not sound compelling and elegant at all. Even though some of the reloading and re-rendering burdens can be lifted by using AJAX these days, this adds more complexity to the app.

Let's go through the advantages and disadvantages of these types of apps.

Advantages:

  • Better SEO performance: Because the client (browser) gets the finished page with all the data and HTML tags, especially the meta tags that belong to the page, search engines can crawl the page and index it.
  • Faster initial load time: Because the pages and content are rendered on the server side by a server-side scripting language such as PHP before sending it to the client browser, we get the rendered page fast on the client side. Also, there is no need to compile the web pages and content in JavaScript files like we do in traditional SPAs, so the app is loaded quicker on the browser.

Disadvantages:

  • Poorer user experience: Because every page has to be re-rendered and this process takes time on the server, the user has to wait until everything is reloaded on the browser and that may affect the user experience. Most of the time, we want the new data only when provided with the new request; we don't need the HTML base to be regenerated, for example, the navigation bar and the footer, but still, we get these base elements re-rendered, regardless. We can make use of AJAX to render just a particular component, but this makes development more difficult and complex.
  • Tight coupling of the backend and frontend logic: The view and data are usually handled together within the same app. For example, in a typical PHP framework app such as Laravel, you may render the view (https://laravel.com/docs/7.x/views) with a template engine such as Laravel Pug (https://github.com/BKWLD/laravel-pug) in a route. Or, if you are using Express for a traditional server-side rendered app, you may use a template engine such as Pug (https://pugjs.org/api/getting-started.html) or vuexpress (https://github.com/vuexpress/vuexpress) for rending the view (https://expressjs.com/en/guide/using-template-engines.html). In these two frameworks for a typical, traditional server-side rendered app, the view is coupled with the backend logic, even though we can extract the view layer with a template engine. The backend developer has to know what view (for example, home.pug) to use for each specific route or controller. On the other hand, the frontend developer has to work on the view within the same framework as the backend developer. This adds more complexity to the project.

Traditional single-page app (SPA)

As opposed to server-side rendered apps, SPAs are client-side rendered (CSR) apps that render content in the browser using JavaScript without requiring new pages to be reloaded during use. So, instead of getting the content rendered to the HTML document, you get barebones HTML from the server, and the content will be loaded using JavaScript in the browser, as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue App</title>
</head>
<body>
<div id="app"></div>
<script src="https://unpkg.com/vue/dist/vue.js" type="text/javascript"></script>
<script src="/path/to/app.js"type="text/javascript"></script>
</body>
</html>

This is a very simple Vue app in which you have a container, <div>, with app as its ID only and nothing else inside it, followed by two <script> elements. The first <script> element will load the Vue.js library, while the second one will load the Vue instance that renders the content of your app, as follows:

// path/to/app.js
const app = new Vue({
data: {
greeting:'Hello World!'
},
template: '<p>{{ greeting }}</p>'
}).$mount('#app')

Let's go through the advantages and disadvantages of this type of app.

Advantages:

  • Better user experience: SPA is fast when rendering content after the initial load. Most resources, such as CSS styles, JavaScript code, and HTML templates, are only loaded once throughout the lifespan of the app. Only data is sent back and forth afterward; the base HTML and layout stay unchanged, thus offering a smooth and better user experience.

  • Easier development and deployment: SPA development is comparatively easier to get started without the need for a server and a server-side scripting language. You can simply kick off the development from your local machine with file://URI. It is easier to deploy as well because it consists of HTML, JavaScript, and CSS files; you can just drop them to the remote server and go live right away.

Disadvantages:

  • Poor performance on the search engine: SPAs are bare-bone single HTML pages, mostly with no headings and paragraph tags for search engine crawlers to crawl. The SPA content is loaded via JavaScript that the crawlers mostly cannot execute, so SPAs usually perform poorly in SEO.
  • Slow initial load time: Most resources such as CSS styles, JavaScript code, and HTML templates are only loaded once throughout the lifespan of the app, so we need to load tons of these resource files all at once at the beginning. By doing this, the app usually slows down regarding its initial loading time, especially in a large SPA.

Universal server-side rendered app (SSR)

As we learned in the previous section, there are advantages and disadvantages to both traditional server-side rendered apps and SPAs. There are benefits in writing SPAs, but there are things that you lose: the ability for web crawlers to traverse your app and slower performance while the app is initially loaded. This is the opposite of writing traditional server-side rendered apps, also there are things you do not have, such as better user experience and the fun of client-side development in SPAs. Ideally, client-side and server-side rendering can be balanced for user experience and performance. Here is where universal server-side rendering (SSR) comes to bridge the gap.

JavaScript has become an isomorphic language since the release of Node.js in 2009. By isomorphic, we mean that codes can run both on the client side and the server side. Isomorphic (universal) JavaScript can be defined as a hybrid of client-side and server-side applications. It is a new approach for web apps to compensate for the shortcomings of both traditional SSR apps and traditional SPAs. This is the category that Nuxt falls into.

In universal SSR, your app will first pre-load on the server side, pre-render the pages, and send the rendered HTML to the browser before switching to the client-side operation for the rest of its lifespan. Building universal SSR apps from scratch can be tedious as it requires lots of configuration before the actual development process begins. This is what Nuxt aims to achieve by presetting all the configuration needed for you to create SSR Vue apps easily.

Even though universal SSR apps are a great solution in our modern web development, there are still advantages and disadvantages to these types of apps. Let's go through them.

Advantages:

  • Faster initial load time: In universal SSR, JavaScript and CSS are split into chunks, assets are optimized, and pages are rendered on the server-side before being served to the client browser. All of these options help make the initial loading time faster.
  • Better SEO support: Since all pages are rendered on the server side with the appropriate meta content, headings, and paragraphs before being served on the client side, the search engine crawlers can traverse the page to increase the SEO performance of your app.
  • Better user experience: Universal SSR apps work like traditional SPAs after the initial load in that the transition between pages and routes is seamless. Only data is transmitted back and forth without re-rendering the HTML content holders. All these features have helped to provide a better user experience overall.

Disadvantages:

  • Node.js server required: Running JavaScript on the server side requires a Node.js server, so the server must be set up before you can use Nuxt and write your app.
  • Complex development: Running JavaScript code in universal SSR apps can be confusing because some JavaScript plugins and libraries are meant to run on the client side only, such as Bootstrap and Zurb Foundation for styling and DOM manipulation.

Static-generated app

Static-generated apps are pre-generated with the help of a static site generator and stored as static HTML pages on the hosting server. Nuxt comes with a nuxt generate command that generates static pages out of the box for you from the universal SSR or SPA app that you've developed in Nuxt. It pre-renders HTML pages for each of your routes into a generated /dist/ folder during the build step, as follows:

-| dist/
----| index.html
----| favicon.ico
----| about/
------| index.html
----| contact/
------| index.html
----| _nuxt/
------| 2d3427ee2a5aa9ed16c9.js
------| ...

You can deploy these static files to a static hosting server without the need for Node.js or any server-side support. So, when the app is initially loaded on the browser no matter what route you are requesting you will always get the full content (if it's been exported from the universal SSR app) immediately, and the app will perform like a traditional SPA afterward.

Let's go through the advantages and disadvantages of these types of apps.

Advantages:

  • Fast initial load time: Since each route is pre-generated as a static HTML page that has its own content, it is fast to load on the browser.
  • Good for SEO: Static-generated web apps allow your JavaScript app to be crawled perfectly by search engines, just like traditional server-side rendered apps.
  • Easier deployment: Because static-generated web apps are just static files, this makes them easy to deploy to static hosting servers such as GitHub Pages.

Disadvantages:

  • No server-side support: Because static-generated web apps are just static HTML pages and run on the client side only, this means there's no runtime support for Nuxt's nuxtServerInit action method and Node.js HTTP request and response objects, which are only available on the server side. All data will be pre-rendered during the build step.
  • No real-time rendering: Static-generated web apps are suitable for apps that only serve static pages that are pre-rendered at build time. If you are developing a complex app that requires real-time rendering from the server, then you should probably use universal SSR instead to utilize the full power of Nuxt.

From these categories, you have probably figured out that Nuxt falls in line with universal SSR apps and static-generated apps. Apart from this, it also falls in line with single-page apps, but not the same as traditional SPAs, which you will find out more about in Chapter 15, Creating an SPA with Nuxt.

Now, let's take a better look at Nuxt regarding the types of applications that you will be creating in this book. We'll start with Nuxt as a universal SSR app.

 

Nuxt as a universal SSR app

Many years ago, we had server-side scripting languages such as ASP, Java, server-side JavaScript, PHP, and Python to create traditional server-side apps with template engines to render the view of our apps. This resulted in the tight coupling disadvantage that we went through in the previous section.

So, with the rise of universal SSR frameworks such as Nuxt, Next (https://nextjs.org/), and Angular Universal (https://angular.io/guide/universal), we can utilize their full power to decouple the view from the server-side scripting app for good by replacing the template engine, such as Pug (https://pugjs.org/), Handlebars (https://handlebarsjs.com/), Twig (https://twig.symfony.com/), and many more that we have been deeply replying on. If we consider Nuxt a frontend server-side app and Express (or others) a backend server-side app, we can see how they complement each other perfectly. For example, we can use Express to create a backend server-side app for serving data in JSON format on an API route (for example, /) at localhost:4000:

{
"message": "Hello World"
}

Then, on the frontend server side, we can use Nuxt as a universal SSR app running on localhost:3000 to consume the aforementioned data by sending an HTTP request from a page in our Nuxt app, as follows:

// pages/index.vue
async asyncData ({ $http }) {
const { message } = await $http.$get('http://127.0.0.1:4000')
return { message }
}

Now, we have Nuxt as both a server and a client that handles our app's view and templates, while Express just handles our server-side logic. We no longer need a template engine to present our content. So, for once, perhaps we don't need to learn so many template engines and we don't need to worry about the battle between them because we now have the universal one – Nuxt.

We will show you how to create cross-domain apps with Nuxt and Koa (another Node.js server-side framework similar to Express) in Chapter 12, Creating User Logins and API Authentication.

Note that in the preceding code, we used the Nuxt HTTP module to make the HTTP request. However, we will mostly use vanilla Axios or the Nuxt Axios module throughout this book for HTTP requests. For more information about the Nuxt HTTP module, please visit https://http.nuxtjs.org/.

You also can use the Nuxt Content module to act as headless CMS so that you can serve your app content from Markdown, JSON, YAML, XML, and CSV files that can be stored "locally" in your Nuxt project. However, in this book, we will be using and creating external APIs to serve our content in order to avoid the tightly coupled issue that we found in the traditional server-side apps in the first place. For more information about the Nuxt Content module, please visit https://content.nuxtjs.org/.
 

Nuxt as a static site generator

Even though server-side rendering is the main feature of Nuxt, it is also a static site generator that pre-renders your Nuxt app in a static site, as shown in the example provided for the static-generated app category. It is perhaps the best of both worlds between a traditional single-page application and a server-side-rendered app. While benefiting from the static HTML content for a better SEO, you no longer need the runtime support from Node.js and Nuxt. However, your app will still behave like an SPA.

What's more is that during static generation, Nuxt has a crawler that crawls the links in your app to generate dynamic routes and save their data from the remote API as payload.js files in a /static/ folder inside the /dist/ folder. These payloads are then used to serve the data that was originally requested from the API. This means you are not calling the API anymore. This can secure your API from the public, and possibly from attackers.

You'll learn how to generate static sites from Nuxt with a remote API in Chapter 14, Using Linters, Formatters, and Deployment Commands, and in the final chapter of this book, Chapter 18, Creating a Nuxt App with CMS and GraphQL.

 

Nuxt as a single-page app

Nuxt is well-suited for developing single-page apps if you have any reason that prevents you from using Nuxt as a server-side rendering app. As we mentioned at the beginning of this chapter, Nuxt comes with two modes for developing your app: universal and spa. This means you just have to specify spa in the mode property in your project configuration, which we'll explore in more detail in the next chapter.

So, you might be thinking that if we can use Nuxt for developing a SPA, then why bother with Vue anymore? In fact, the SPA you can develop from Nuxt is slightly different from the SPA from Vue. The SPA you build from Vue is a traditional SPA, while the SPA from Nuxt is a "static" SPA (let's refer to it as Nuxt SPA) your app pages are pre-rendered at build time. This means deploying a Nuxt SPA is technically the same as statically generating a Nuxt universal SSR app both require the same Nuxt command: nuxt generate.

This can be confusing and you may want to ask what is the difference between the static-generated SSR app and the static-generated SPA? The difference is very obvious the static-generated SPA has no page content compared to the static-generated SSR app. The static-generated SPA is pre-rendered with your app pages and "empty" HTML, just like the traditional SPA – devoid of page content. This is confusing, but rest assured, we will figure all this out in the upcoming chapters of this book. In particular, you learn about the trade-offs of developing SPAs in Nuxt and how to overcome them.

You'll learn how to develop a Nuxt SPA and generate a static Nuxt SPA with a remote API in Chapter 15, Creating an SPA with Nuxt.

 

Summary

Well done! You have made it through the first chapter of your journey into Nuxt. In this chapter, you learned what makes up the Nuxt framework; that is, Vue (the origin of Nuxt), webpack, and Babel. You learned about the various features Nuxt provides, such as the ability for you to write Vue single-file components (.vue files), ES2015+ JavaScript (ES6), CSS with a preprocessor (Sass, Less, Stylus). You are also able to extend your app with modules and plugins, to add transitions between the routes of your app, to manage the <head> element and the meta content of each route or page in your app. Apart from this you also covered tons of great features that are imported from webpack and Babel, such as bundling, minifying, and splitting code. You also learned that you can access tons of plugins and modules from the Nuxt community for your Nuxt projects.

Apart from these great features, you learned about the pros and cons of each type of available application: traditional server-side rendered apps, traditional single-page apps (SPAs), universal server-side rendered apps (SSRs), and static-generated apps. You also learned that Nuxt apps actually fall in line with the categories of universal SSR apps and static-generated apps. And then, you learned that Nuxt also falls in line with single-page apps, but not the same as traditional SPAs. Lastly, you looked into using Nuxt for universal SSR apps, static-generated apps, and single-page apps, all of which you'll learn more about throughout this book.

In the next chapter, you will learn how to install Nuxt and create a simple Nuxt app and understand the default directory structure that comes with the Nuxt scaffolding tool. You will also learn how to customize your Nuxt app and understand the assets that are served in Nuxt. So, stay tuned!

About the Author
  • Lau Tiam Kok

    Lau Tiam Kok, aka Lau Thiam Kok, is a cross-disciplinary full stack web developer/designer and analyst. He was born in Penang, Malaysia. His studies include a Bachelor of Applied Arts degree at University Malaysia Sarawak (1996 - 1999), and an MSc in Digital Futures at the Institute of Digital Art and Technology, University of Plymouth, UK (2002 - 2003). Lau has freelanced for more than 10 years for various individuals, institutions, and companies. He works with designers or independently, from designing layouts to coding the frontend and server-side programs to produce responsive websites. He also works collaboratively on air-quality monitoring projects for Citizen Sense (based in the United Kingdom), which uses R, openair, Shiny, MongoDB, RethinkDB, Express.js, Koa.js, Socket.IO and Nuxt.js for data analysis web apps and IoT data platforms.

    Browse publications by this author
Latest Reviews (1 reviews total)
A lot of well explained samples
Hands-on Nuxt.js Web Development
Unlock this book and the full library FREE for 7 days
Start now