The author selected the Tech Education Fund to receive a donation as part of the Write for DOnations program.
Introduction
AdonisJs is a Node.js web framework written in plain JavaScript that runs on all major operating systems. It uses the popular MVC (Model – View – Controller) design pattern and offers a stable ecosystem for writing server-side web applications. The framework features seamless authentication, SQL ORM (object-relational mapping), migrations, and database seeding. AdonisJs has a similar architecture to the PHP web application framework Laravel, including the same folder structure and several shared setup concepts.
By default, AdonisJs uses the Edge template engine that is designed for intuitive use. Just like Laravel, AdonisJs ships with an ORM called Lucid that serves as an interface for communication between an application’s models and the database. With AdonisJs, developers can build a full-stack application where the back-end server will be responsible for applying the business logic, routing, and rendering all the pages for the application. It is also possible to create a web service API to return JSON responses from a controller; these web services can then be consumed using front-end frameworks such as Vue.js, React, and Angular.
In this tutorial, you’ll build an application with AdonisJs using its CLI. You’ll create routes, controllers, models, and views within your application and you’ll carry out form validations. The example in this tutorial will be an inspirational quote application in which a user can sign up and log in to create an inspirational quote. This demo application will give you the opportunity to carry out CRUD (Create, Read, Update, and Delete) operations.
Prerequisites
Before you begin this guide, you will need the following:
- A local installation of Node.js (at least v8) and npm (at least v3.0). Node.js is a JavaScript run-time environment that allows you to run your code outside of the browser. It comes with a pre-installed package manager called npm, which lets you install and update packages. To install these on macOS or Ubuntu 18.04, follow the steps in How to Install Node.js and Create a Local Development Environment on macOS or the Installing Using a PPA section of How To Install Node.js on Ubuntu 18.04.
- MySQL installed on your machine. Follow the instructions here to download and install it for your choice of the operating system. To successfully install MySQL, you can either install it by using Homebrew on Mac or for Ubuntu 18.04 follow our tutorial How To Install MySQL on Ubuntu 18.04.
- A basic understanding of JavaScript; see our How To Code in JavaScript series.
- A text editor installed, such as Visual Studio Code, Atom, or Sublime Text.
Note: This tutorial uses a macOS machine for development. If you’re using another operating system, you may need to use sudo
for npm
commands in the first steps.
Step 1 — Installing the Adonis CLI
In this section, you will install Adonis CLI and all its required packages on your local machine. The CLI will allow you to scaffold a new AdonisJs project as well as create and generate boilerplate for controllers, middlewares, and models in your application. You’ll also create your database for the project.
Run the following command to install the AdonisJs CLI globally on your machine via npm
:
- npm i -g @adonisjs/cli
Once the installation process is complete, type the following command in the terminal to confirm the installation of AdonisJs and view the current version:
- adonis --version
You will see output showing the current version of AdonisJs:
Output4.1.0
With the successful installation of the AdonisJs CLI, you now have access to and can use the adonis
command to create fresh installations of an AdonisJs project, manage your project, and generate relevant files such as the controllers, models, etc.
Now, you can proceed to create a new AdonisJs project by using the adonis
command as shown here:
- adonis new adonis-quotes-app
The preceding command will create an application named adonis-quotes-app
in a new directory with the same name in your local project directory with the relevant AdonisJs MVC structure.
Move into the new application folder:
- cd adonis-quotes-app
Then start your application by running:
- adonis serve --dev
This will start the development server on the default port 3333
as specified inside the root .env
file for your application. Navigate to http://localhost:3333 to view the welcome page of AdonisJs.
Now you’ll complete the setup of your database. Here, you’ll install the mysql
driver to connect to your MySQL server from your Node.js application via npm
. To begin, go back to your terminal where the application is currently running, stop the process with CTRL + C
and run the following command:
- npm i mysql
Now that you have successfully installed the MySQL Node.js driver for this application, you need to create the application database and set up the appropriate connection to it.
The latest version of MySQL that you have installed from the prerequisite tutorial uses a default authentication plugin named caching_sha2_password
. This is currently not supported by Node.js drivers for MySQL. To avoid any database connection issue from your application, you will need to create a new MySQL user and use the currently supported authentication plugin—mysql_native_password
.
To begin, access the MySQL client using the root account:
- mysql -u root -p
You will be prompted to enter your root account password set up during the MySQL installation.
Next, create the user and password using the mysql_native_password
plugin:
- CREATE USER 'sammy'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
You will see the following output:
OutputQuery OK, 0 rows affected (0.02 sec)
Next, create a database for the application with:
- CREATE DATABASE adonis;
You will see the following output:
OutputQuery OK, 1 row affected (0.03 sec)
You’ve now successfully created the database for this application.
Now, enable access to the created database for the new MySQL user. Run the following command to grant all privileges to the user in the database:
- GRANT ALL PRIVILEGES ON adonis.* TO 'sammy'@'localhost';
Reload the grant tables by running the following command to apply the changes that you just made:
- FLUSH PRIVILEGES;
You will see the following output:
OutputQuery OK, 0 rows affected (0.00 sec)
Exit the MySQL client with:
- quit;
You’ve successfully installed the AdonisJs CLI, created a new AdonisJs project, and installed mysql
via npm
. You also created the database for this application and set up a MySQL user with the appropriate privileges to it. This is the basic setup for your application and in the next section you will begin to create the necessary views for your application.
Step 2 — Using the Edge Templating Engine
AdonisJs is shipped with its own template engine called Edge. It allows you to create a reusable HTML template and enables the introduction of front-end logic into your application with minimal code. Edge provides JavaScript developers with the tools while developing an application to build a component-based layout, write conditionals, use iterations, and create view layers to hold logic. All template files end with the .edge
extension and are stored in the resources/views
directory.
The following are the views that your application will need to function properly:
- Master Layout: With Edge, you can create a page that will contain the CSS, common JavaScript files, jQuery, and common parts of the user interface that will stay the same throughout the application—for example, the navigation bar, logo, header, etc. Once you’ve established the Master Layout page, other views (pages) in your application will inherit it.
- Index view: This page will use the master layout to inherit common files and will also render contents for the homepage of the application.
- Login page: This page will also use the master layout and render the form with the input fields for both username and password for users to log in.
- Register page: Here, users will see a form to register and have their details persisted into the database.
- Create quote page: Users will use this page to create an inspirational quote.
- Edit quote page: Users will use this page to edit a quote.
- View quote page: Users will use this page to view a particular quote.
To begin, use the adonis
command to create the master layout page by running the following command:
- adonis make:view layouts/master
You’ll see output similar to the following:
Output✔ create resources/views/layouts/master.edge
This command will automatically create a master.edge
file in your resources/views/layouts
folder. Open the new file:
- nano resources/views/layouts/master.edge
Add the following code in it:
adonis-quotes-app
{{ style('https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css') }}
{{ style('style') }}
{{ script('https://code.jquery.com/jquery-3.3.1.slim.min.js') }}
@include('navbar')
@!section('content')
{{ script('https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js') }}
In this file, you include the CDN files for Bootstrap CSS, Bootstrap JavaScript, and jQuery. You add a global CSS file name of style.css
and within the div
you include a partial file named navbar
. To reuse fragments of HTML code that you require across multiple pages in your application, like nav
or footer
, you can incorporate partials. These are smaller files containing the repeated code making it quicker to update code for these elements in one place rather than at every instance it occurs. The navbar
contains markup for a Login and Register buttons, a logo, and a home link.
With this in place, all the subsequent pages that will be created for this application can extend the master layout and have the navbar
rendered without the need to write the content all over again. You’ll create this navbar
file later in the tutorial.
Finally, you define a section tag @!section()
to include content from other pages and have them rendered by the master layout. For this to work as expected, all the new pages that will extend the master layout must also define a section tag with the same name (i.e., @section(
'
content
'
)
).
Save and exit the file once you’re finished editing it.
Next, you will use the adonis
command to create the navigation bar:
- adonis make:view navbar
You’ll see output similar to:
Output✔ create resources/views/navbar.edge
Open the newly created file:
- nano resources/views/navbar.edge
Then add the following code to it:
In addition to defining the links to the homepage and a button to register and login, you add a @loggedIn
tag. With this in place you can write a conditional statement around the authenticated user and display appropriate contents where necessary. For an authenticated user, the application will display their username and a button to create a new quote. If a user is not logged in, your application will display a button to either log in or register. This page will be included as a partial on every page as it was earlier in the master layout for this application.
Save and exit the file.
Now, you’ll create the index page that you’ll use for the application’s homepage. It will render and display the list of all inspirational quotes that users write:
- adonis make:view index
You will see an output similar to the following:
Output✔ create resources/views/index.edge
The file created here will be located in resources/views/index.edge
. Open the file:
- nano resources/views/index.edge
Then add the following code:
@layout('layouts/master')
@section('content')
@if(flashMessage('successmessage'))
{{ flashMessage('successmessage') }}
@endif
@each(quote in quotes)
@else No inspirational quote has been created
@endeach @endsection
Here, you indicate that this view will use the master
layout by extending it. This page can now have access to all the libraries, stylesheets, and the navbar
included in the master
layout. Next, you iterate over an array of quotes
using the built-in @each
tag. The quotes
array will be passed to this view from the QuoteController
that you’ll create later in this tutorial. If there are no quotes, an appropriate message will be displayed.
Save and exit this file.
Now, to create the login page, run the following command from the terminal:
- adonis make:view auth/login
You will see an output similar to:
Output✔ create resources/views/auth/login.edge
This will automatically create an auth
folder within resources/views
and also create a login.edge
file within it. Open the login.edge
file:
- nano resources/views/auth/login.edge
Add the following content:
@layout('layouts/master')
@section('content')
@endsection
This file holds a form that contains input elements that you’ll use to collect the username and password of a registered user before they can successfully get authenticated and start creating quotes. Another important element to note on this page is the {{ csrfField() }}
. It is a global variable that AdonisJs will use to pass the CSRF access token when sending a POST
, PUT
, and DELETE
request from your application.
This was put in place to protect your application from Cross-Site Request Forgery (CSRF) attacks. It works by generating a unique CSRF secret for each user visiting your website and once your users send an HTTP request from the frontend, a corresponding token is generated for this secret and passed along with the request. This will allow the middleware created for this request within AdonisJs to verify that both the token and CSRF secret is valid and belong to the currently authenticated user.
Save and exit the file once you’re finished.
Next, you will create the register page with this command:
- adonis make:view auth/register
You will see output similar to this:
Output✔ create resources/views/auth/register.edge
Locate and open the newly created file in resources/views/auth/register.edge
:
- nano resources/views/auth/register.edge
Add the following code:
@layout('layouts/master')
@section('content')
@endsection
Similarly to what you have on the login page, this file contains an HTML form with input fields to collect the name
, email
, and password
of a user during the registration process. Also included is the {{ csrfField() }}
as it is required for each post request for an AdonisJs application.
Save and exit the file.
Now, you will generate a new file to create an inspirational quote by running the following command from the terminal:
- adonis make:view quotes/create-quote
You will see output like:
Output✔ create resources/views/quotes/create-quote.edge
Open resources/views/quotes/create-quote.edge
:
- nano resources/views/quotes/create-quote.edge
And add the following content to it:
@layout('layouts/master')
@section('content')
This page extends the master layout and contains an HTML form with a text area element that allows a user to input text over multiple rows before being posted and handled by the appropriate route.
Save and exit the file once you’re finished.
Next, you will create a page for editing a particular quote. Run the following command from the terminal:
- adonis make:view quotes/edit-quote
You will see the following output:
Output✔ create resources/views/quotes/edit-quote.edge
Open the file with:
- nano resources/views/quotes/edit-quote.edge
Add the following content to resources/views/quotes/edit-quote
:
@layout('layouts/master')
@section('content')
@endsection
This page holds similar content as the create-quote.edge
file—the difference is that it contains the details of a particular quote that needs to be edited,