What is Nuxt.js?
The objective of Nuxt.js is to make the creation of universal Vue.js applications easier - universal meaning both the client and server sides.
This is achieved by abstracting the client and server, so that our programming is independent of where it is running.
One example of what Nuxt.js can do is: imagine we have a page displaying cryptocurrencies with their name, symbol, logo and price. In a client-side application, we would fetch the data from the endpoint, and the corresponding Vue.js component would take care of modifying the DOM of the page to show the data.
By running the same code server-side with Nuxt.js, we will receive the same page rendered, connected to the same endpoints with the populated data, and the generated DOM in the form of HTML in the browser.There is more though. Our application, as we have received it, is still reactive, so we can update prices periodically by calling the same endpoint, but this time on the client side. We don't lose that reactivity that we like from Vue.js.
This is a huge advantage because with the same code, we can have a website that is SEO-friendly just by creating it using Nuxt.js.
This tutorial relies heavily on what we have learned as a result of the solutions we applied to our project https://cryptoticker.cc/, a free cryptocurrency exchanges comparison tool built using Nuxt.js in a short amount of time. Examples we'll be using will be based on scenarios related to that project.
If you already have a Vue.js project, and you want to convert it to Nuxt.js; you will have to do that from scratch. While that may sound challenging, it is easier than it seems. I will provide some guidance, specifically on that, at the end of this article, but if you follow the next steps, you will more than likely be able to do that on your own.
First, let us create our Nuxt.js project. For that, you need yarn to be installed globally on your machine:
1$ yarn create nuxt-app <my-project>
Then, the wizard will ask you some questions:
- Project name - This will map to
package.json
name - Project description - This will map to
package.json
description - Use a custom server framework - If you want to integrate a server framework on the same app, choose whichever you like. Personally, I don’t use it for my projects.
- Choose features to install - Choose wisely depending on your needs but usually, I require all of them. PWA support is a necessity in my opinion.
- Use a custom UI framework - You can choose if you want a UI framework to be installed and configured in your app. I usually use Vuetify.
- Use a custom test framework - Use the one you like or none.
- Choose rendering mode - Here you must choose Universal. You can switch modes later if you want to, but this one is necessary to build an SSR website.
- Author name
- Choose package manager (I recommend
yarn
)
After it's done installing, navigate to your project $ cd <my-project>
Creating our routes
This step is fairly simple. The project structure for Nuxt.js is very similar to a Vue.js project. One of the most significant differences is that the routes are generated dynamically by Nuxt.js based on your page's folder structure.
So, imagine we want to create the following: A homepage route that we want to be the main landing for our users to quickly discover exchanges. Then, we have a compare route, where we want the user to be able to compare cryptocurrencies from different exchanges. Finally, we want a dynamic route that will take an exchange key and display the details. All this can be configured by the way we name the files and folders inside the page's directory. This will be our page's folder structure:
pages
├── exchanges
│ ├── _key
│ ├── index.vue // route will be "/exchanges/:key"
├── index.vue // route will be "/"
├── compare.vue // route will be "/compare"
That’s it! We don’t need to configure anything else. Our app will now be ready to serve these pages. If you want to learn more about routing and the built-in properties for the page components, look at the Nuxt.js routing documentation.
Pre-populate Page Data
To be able to serve the browser a fully-rendered page that is SEO-friendly and contains the necessary keywords, we need to fetch the data on the server side.
Nuxt.js provides us with a useful property on the pages components called asyncData, which is essentially like the normal Vue.js data property except it is resolved on the server.
If we installed axios, we can do the following to get exchanges data on the server side:
1async asyncData({
2 params,
3 $axios
4}) {
5 const {
6 data
7 } = await $axios.get(`/api/exchanges/${params.key}`)
8 return {
9 exchangesData: data
10 }
11}
You can then use “exchangesData” anywhere in your template including computer properties, methods, and more. It will be resolved before the page is served to the client.
The property “exchangesData” will still be reactive and if you assign a new value - for example if you request new data, it will react to the changes.
Global, Page specific and Dynamic Page Meta tags
Nuxt.js provides us with an almost effortless and maintainable way of adding meta tags to our website. We can configure the global meta tags on the head property of nuxt.config.js
.
Meta tags will be added to every page of your website. It is very important to add the hid property to the meta object because it will prevent duplicates that can severely impact your SEO.
For example, this could be a head property in our nuxt.config.js
.
1// ... import stuff here
2
3export default {
4 // ... other configuration properties here
5 /*
6 ** Headers of the page
7 */
8 head: {
9 title: 'Crypto Ticker',
10 meta: [
11 { charset: 'utf-8' },
12 {
13 hid: 'viewport',
14 name: 'viewport',
15 content: 'width=device-width, initial-scale=1'
16 },
17 {
18 hid: 'twitter:card',
19 name: 'twitter:card',
20 content: 'Cryptocurrency Compare Tool | 2amigOS'
21 },
22 { hid: 'twitter:site', name: 'twitter:site', content: '@2amtech' },
23 { hid: 'twitter:creator', name: 'twitter:creator', content: '@2amtech' },
24 {
25 hid: 'twitter:title',
26 name: 'twitter:title',
27 content: 'Crypto Ticker - A cryptocurrency comparison tool'
28 },
29 {
30 hid: 'twitter:description',
31 name: 'twitter:description',
32 content: pkg.description
33 },
34 {
35 hid: 'twitter:image',
36 name: 'twitter:image',
37 content: '/crypto-ticker-snapshot'
38 },
39 { hid: 'description', name: 'description', content: pkg.description },
40 {
41 hid: 'og:image',
42 property: 'og:image',
43 content: '/crypto-ticker-snapshot.png'
44 },
45 {
46 hid: 'og:site_name',
47 name: 'og:site_name',
48 content: '2amigOS Crypto Ticker'
49 },
50 { hid: 'og:title', name: 'og:title', content: 'Crypto Ticker' },
51 {
52 hid: 'og:description',
53 name: 'og:description',
54 content: pkg.description
55 }
56 ],
57 link: [
58 { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
59 {
60 rel: 'stylesheet',
61 href:
62 'https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons'
63 }
64 ]
65 },
66
67 // ... more configuration options here ...
68}
69
70
These global meta tags are useful but what if we want to add meta tags that are specific to our pages? Also, what if this page is dynamic, such as a details page? For that, we can use the head property of our page components. This head has the context of the component and therefore you have access to your data properties.
1// ... other code
2head() {
3 return {
4 title: this.title,
5 meta: [{
6 hid: 'description',
7 name: 'description',
8 content: this.exchange.details
9 }, {
10 hid: 'twitter:card',
11 name: 'twitter:card',
12 content: `Crypto Ticker - ${this.exchange.name}`
13 }, {
14 hid: 'twitter:title',
15 name: 'twitter:title',
16 content: `Crypto Ticker - ${this.exchange.name}`
17 }, {
18 hid: 'twitter:description',
19 name: 'twitter:description',
20 content: this.exchange.details
21 }, {
22 hid: 'og:title',
23 name: 'og:title',
24 content: `Crypto Ticker - ${this.exchange.name}`
25 }, {
26 hid: 'og:description',
27 name: 'og:description',
28 content: this.exchange.details
29 }]
30 };
31}
32// ... other code
That’s it! Every detail route will have a meta tag with dynamic content. That’s awesome!
Add Google Analytics
Adding Google Analytics in a Nuxt.js app is very easy. Start by running the following command:
$ yarn add @nuxtjs/google-analytics
1$ yarn add @nuxtjs/google-analytics
Then, go to your application config in nuxt.config.js
and add the following to the modules array:
1
2// ... other configuration options
3modules: [
4 '// ... other modules
5 '@nuxtjs/google-analytics' // <--- This one!
6 ],
7
8// ... more configuration options here ...
Now you can configure Google Analytics. Add this at the root level of the nuxt.config.js
object:
1googleAnalytics: {
2 id: "{YOUR GOOGLE ANALYTICS ID}",
3 dev: false
4 },
5
Hint
If instead of hardcoding the values you want to use environment variables, I highly recommend you to use the dotenv package.
To make sure everything works, run your app with yarn dev and open the console. You should see the Google Analytics logs.
If you need more information about the analytics module, you can go to the nuxt github: https://github.com/nuxt-community/analytics-module
Add a Dynamic Sitemap
We can also add a dynamic sitemap into our build process by adding the Nuxt sitemap module. First, we must install it by running the following command:
1$ yarn add @nuxtjs/sitemap
Then, in the same way as we did for Google Analytics, we add it to our modules array inside nuxt.config.js.
1
2// ... other configuration options
3modules: [
4 // ... other modules
5 '@nuxtjs/sitemap' // <--- This one!
6 ],
7
8// ... more configuration options here ...
After that we can configure the sitemap build with the sitemap property in nuxt.config.js.
Check the following code - we mapped the array of routes to return an array of objects with changefreq, priority, lastmodISO and route properties. This is much easier to read than hardcoding route config object and repeating that process for each route:
1sitemap: {
2 path: '/cryptoticker.cc.xml',
3 hostname: 'https://cryptoticker.cc',
4 cacheTime: 1000 * 60 * 15,
5 gzip: true,
6 generate: false,
7 routes: [
8 '/',
9 '/compare',
10 '/exchanges/bibox',
11 '/exchanges/binance',
12 '/exchanges/bitfinex',
13 '/exchanges/bittrex',
14 '/exchanges/coss',
15 '/exchanges/kraken',
16 '/exchanges/kucoin',
17 '/exchanges/poloniex',
18 '/exchanges/theocean',
19 '/exchanges/upbit'
20 ].map(route => ({
21 url: route,
22 changefreq: 'monthly',
23 priority: 1,
24 lastmodISO: new Date().toISOString().split('T')[0]
25 }))
26 },
You can check if the sitemap is added correctly by building your app with yarn build, then launching the server with yarn start, and checking in your localhost:port/sitemap.xml
. For more information about the sitemap module check https://github.com/nuxt-community/sitemap-module#readme.
Nuxt.js is very powerful and there is much more that you can do with it. This is only a small example of what’s possible. If you liked this tutorial and want to see a very practical example of how I used all of this together, please visit our free tool made using Nuxt.js.
Accelerate Your Career with 2am.tech
Join our team and collaborate with top tech professionals on cutting-edge projects, shaping the future of software development with your creativity and expertise.
Get Started