Hazem Allbabidi

February 24, 2024 | 7 min read


Nuxt JS in Less Than 10 Minutes

Nuxt JS is a popular JavaScript framework that uses Vue JS to offer a production-grade full-stack web framework. In addition to the speed and simplicity that Vue JS provides, Nuxt JS offers Server-Side Rendering, Built-in State Management, Dynamic Routing, and much more.

In this article, we will go through the basic setup for a Nuxt JS (version 3) web application, setting up a couple of pages (with dynamic page routes), and finally, create and connect to an API that we will build in the same application with the help of Nitro.

Prerequisites

Having Vue JS knowledge or experience is preferred but not mandatory. But it is essential to have JavaScript knowledge and/or experience.

You will also need to have a laptop/PC with internet access, as well as Node JS.

Setting It Up

First, you need to open the terminal since we will need to run a few commands. After you have opened the terminal, navigate to the directory where you wish to keep the project files inside of.

Next, create the application by running the command below:

npx nuxi@latest init nuxt-tutorial

Note: you can replace the nuxt-tutorial with your preferred app name.

Next, access the app directory by running:

cd nuxt-tutorial

Now, install the dependencies needed to run and build the application:

npm install

Lastly, start up the application by running:

npm run dev

You can now access the URL http://localhost:3000/ on your browser. You should see a page with the title “Welcome to Nuxt JS!”.

Pages

In Nuxt 3, the app comes in with 1 Vue file by default, called app.vue which is located in the application root directory. This (default) method of serving pages is fine if you have only one page, but since we will be having more than one page, we need to replace the content of the app.vue file to:

<template>
	<div>
		<NuxtPage />
	</div>
</template>

This will basically convert this “main” Vue file into a router for ther other pages in the system.

To create new pages, first, create a directory in the root folder titled pages. Inside it, create two files:

  1. index.vue
  2. [id].vue

The first file will be the main or root page for the web app, which will appear when the user is on the / path. The second file, is a dynamic file that allows the value to be changed. For example, if the user accesses /1 or /123, then they will be directed to the same page, but the content will differ based on the value in the path.

Inside the index.vue file, we can add a simple Hello World along with the basic Vue code:

<template>
	<div>
		<h1>Hello World</h1>
	</div>
</template>

Next, inside the [id].vue file, we can add temporary code to make sure everything is working fine till now:

<template>
	<div>
		{{ $route.params.id }}
	</div>
</template>

The $route is a Nuxt JS value which displays data about the current page route. In this case, we are accessing the route parameters (i.e. $route.params) and from there, we are fetching the value id. The reason it is called id is because that is the name written in the file name: [id].vue. We can change the file name and content to other names, such as [application_name].vue and $route.params.application_name. But we will stick with id for now.

To test everything out. Open the application on your browser at localhost:3000, on the first page, you should see Hello World written on the page. Now, change the path to any value, such as, localhost:3000/123. This should redirect you to a page that displays the value from the URL, which is 123 in this case.

Now that we built a couple of pages, including a dynamic route page, we can move on to creating a simple Back-End API using the built-in engine, Nitro.

Building The API

We will build an API using Nitro that includes 1 route:

To start, create a folder inside the server directory called api. This will create routes that start with /api. Next, create a file inside the api directory titled [id].ts. Inside this file, we will do the following:

  1. Set up the API function
  2. Find the object with the provided ID from an array of objects
  3. Return the result of the search

To begin, create the API function:

export default defineEventHandler(async (event) => {

})

This defines an event handler, which acts as our API.

Next, define the array of objects as a variable. You can use the example I wrote which is provided here:

let  cars  = [
	{ id:  "1", name:  'BMW' },
	{ id:  "2", name:  'Nissan' },
	{ id:  "3", name:  'Honda' },
	{ id:  "4", name:  'Mercedes-Benz' },
]

Next, we need to accept the path parameter, then use it to find the object with the provided ID:

const id = getRouterParam(event, 'id')

let car = cars.find(car => car.id == id)

Note: the getRouterParam is a built-in function to help you get route parameters.

Finally, we can return the value we found:

return car;

The completed function will look like this:

export  default  defineEventHandler(async (event) => {

	let  cars  = [
		{ id:  "1", name:  'BMW' },
		{ id:  "2", name:  'Nissan' },
		{ id:  "3", name:  'Honda' },
		{ id:  "4", name:  'Mercedes-Benz' },
	]

	const  id  =  getRouterParam(event, 'id')

	let  car  =  cars.find(car  =>  car.id  ==  id)
	
	return  car;

})

To test the function, go to your browser, and navigate to localhost:3000/api/2, this should return an object with the id of 2 and name of Nissan.

Now that we are done with our API, let us connect the Front-End to this function.

Connecting The Front-End To The Back-End

Let us head to the [id].vue file, which will have the connection to the new Back-End.

We will be using the built-in fetch functionality to allow for fast and easy communication with the Back-End.

We will do the following:

  1. Read the route parameters
  2. Use the built-in fetch, along with the route parameters, to retrieve the relevant data
  3. Display the retrieve data

To do this, we will first add a script tag under the HTML code, and inside the the script tag, will be including the necessary function to be able to read the route parameters:

<script  setup>
const route = useRoute()

</script>

Now, we can use the function useFetch to retrieve the data from the Back-End. Under the useRoute line, add the following:

const { data } =  await  useFetch(`/api/${route.params.id}`)

This will retrieve the data from the back-end using the appropriate ID, which was pulled from the route parameters.

Finally, we can display the data in the front-end by editing the HTML:

<template>
	<div v-if="data">
		<h1>ID: {{ data.id }}</h1>
		<h1>Name: {{ data.name }}</h1>
	</div>
</template>

In the code above, we first check if the data exists, this will ensure we do not face any issues accessing the objects value when the object does not exist. Then, we access the data for each of the two values, ID and Name (i.e. data.id and data.name).

To test it out, go to your browser and head to localhost:3000/1, you should see the two titles with the values ID: 1 and Name: BMW. You can change the parameter to see what other values will look like, e.g. localhost:3000/2.

Conclusion

Nuxt JS is one of the most famous JavaScript frameworks right now, and is used in many small, medium, and large companies.

It was one of my favorite JS rameworks to use because of how much functionality it offers with simple accessibility.

Thank you for reading the article, I hope you learned about Nuxt JS and followed the tutorial. See you in the next one!


Previous

Platform Review: O’Reilly

Next

Multi-CPU Node JS: Cluster Module
Sign Up To Binance To Get 10% Off Commission Fees Sign Up To Kucoin