Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Hands-on Nuxt.js Web Development
Hands-on Nuxt.js Web Development

Hands-on Nuxt.js Web Development: Build universal and static-generated Vue.js applications using Nuxt.js

Arrow left icon
Profile Icon LAU THIAM KOK Profile Icon Lau Tiam Kok Kok Lau
Arrow right icon
€36.99
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (2 Ratings)
Paperback Aug 2020 698 pages 1st Edition
eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon LAU THIAM KOK Profile Icon Lau Tiam Kok Kok Lau
Arrow right icon
€36.99
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3 (2 Ratings)
Paperback Aug 2020 698 pages 1st Edition
eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Hands-on Nuxt.js Web Development

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!

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Explore techniques for authentication, testing, and deployment to build your first complete Nuxt.js web app
  • Write cleaner, maintainable, and scalable isomorphic JavaScript web applications
  • Transform your Vue.js application into universal and static-generated web apps

Description

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.

Who is this book for?

The book is for any JavaScript or full-stack developer who wants to build server-side rendered Vue.js apps. A basic understanding of the Vue.js framework will assist with understanding key concepts covered in the book.

What you will learn

  • Integrate Nuxt.js with the latest version of Vue.js
  • Extend your Vue.js applications using Nuxt.js pages, components, routing, middleware, plugins, and modules
  • Create a basic real-time web application using Nuxt.js, Node.js, Koa.js and RethinkDB
  • Develop universal and static-generated web applications with Nuxt.js, headless CMS and GraphQL
  • Build Node.js and PHP APIs from scratch with Koa.js, PSRs, GraphQL, MongoDB and MySQL
  • Secure your Nuxt.js applications with the JWT authentication
  • Discover best practices for testing and deploying your Nuxt.js applications
Estimated delivery fee Deliver to Netherlands

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 14, 2020
Length: 698 pages
Edition : 1st
Language : English
ISBN-13 : 9781789952698
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Netherlands

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Aug 14, 2020
Length: 698 pages
Edition : 1st
Language : English
ISBN-13 : 9781789952698
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 106.97
Front-End Development Projects with Vue.js
€32.99
Hands-on Nuxt.js Web Development
€36.99
Vue.js 3 Cookbook
€36.99
Total 106.97 Stars icon
Banner background image

Table of Contents

25 Chapters
Section 1: Your First Nuxt App Chevron down icon Chevron up icon
Introducing Nuxt Chevron down icon Chevron up icon
Getting Started with Nuxt Chevron down icon Chevron up icon
Adding UI Frameworks Chevron down icon Chevron up icon
Section 2: View, Routing, Components, Plugins, and Modules Chevron down icon Chevron up icon
Adding Views, Routes, and Transitions Chevron down icon Chevron up icon
Adding Vue Components Chevron down icon Chevron up icon
Writing Plugins and Modules Chevron down icon Chevron up icon
Adding Vue Forms Chevron down icon Chevron up icon
Section 3: Server-Side Development and Data Management Chevron down icon Chevron up icon
Adding a Server-Side Framework Chevron down icon Chevron up icon
Adding a Server-Side Database Chevron down icon Chevron up icon
Adding a Vuex Store Chevron down icon Chevron up icon
Section 4: Middleware and Security Chevron down icon Chevron up icon
Writing Route Middlewares and Server Middlewares Chevron down icon Chevron up icon
Creating User Logins and API Authentication Chevron down icon Chevron up icon
Section 5: Testing and Deployment Chevron down icon Chevron up icon
Writing End-to-End Tests Chevron down icon Chevron up icon
Using Linters, Formatters, and Deployment Commands Chevron down icon Chevron up icon
Section 6: The Further Fields Chevron down icon Chevron up icon
Creating an SPA with Nuxt Chevron down icon Chevron up icon
Creating a Framework-Agnostic PHP API for Nuxt Chevron down icon Chevron up icon
Creating a Real-Time App with Nuxt Chevron down icon Chevron up icon
Creating a Nuxt App with a CMS and GraphQL Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
(2 Ratings)
5 star 50%
4 star 0%
3 star 0%
2 star 0%
1 star 50%
Daniel Correa Jan 31, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is one of the most detailed and well explained books that I have read so far. First of all, congratulations to the author.This book is about developing a complete range of different web applications with the use of Nuxt and Vue.js. When I refer to a complete range, we talk about SPA, Universal SSR, and static-generated applications (terms that I didn't understand very well, before reading this book).There are some important elements that I really liked and enjoyed of this book:- The author makes an excellent job explaining almost everything. The book provides excellent introductions to all the topics covered. Just a quick example, in Chapter 01 it explains the differences between the types of applications, SSR, SPA, and Universal SSR. In Chapter 12 (login), it explains what is a session, what is a cookie, what are tokens, and so on. Other books go directly to the code (assuming you already know many concepts), but that is not the case with this book.- For me, this is a book that all front-end developers should read, to get a big picture of the different tools and possibilities that you have when creating web applications. To understand the different types of applications, their advantages, disadvantages, and when to use them.- Examples in the GitHub repo worked properly. Examples are simple and provide a proper picture of each topic. However, there is a lack of design styles. So, you will get ugly user interfaces (but you can improve them with the use of a CSS framework such as bootstrap) not a big deal.- The book covers many interesting topics such as, (i) vue essentials (vue files, components, plugins, vuex, and vue-router, among others), (ii) middlewares (to create backend and front-end applications and connect them), (iii) nuxt elements (routes, pages, views, configs, and many more), and (iv) others (such as authentication, logins, database management with mongodb, testing, linters, and graphql, among others).Final notes:- I really recommend to have a little experience working with vue.js. The author presents a lot of examples with vanilla vue.js. However, I suggest playing around with vue.js, and then read this book.- I also recommend having some experience with web development. Because there are many different topics which can be a little overwhelming. But again, the author makes an excellent job explaining each topic.
Amazon Verified review Amazon
Payton Michaels Jan 27, 2021
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
90% of the code doesn't work. I provided some corrections early on and was contacted by packt (as a complete beginner) with a request from the author to further correct the book.I dont think the author actually knows anything about the nuxt framwork.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela