Building a Production-Ready Node.js Web API with Sails.js
Getting Started with Sails.js
To get started, we’ll need to install the Sails.js CLI tool globally on our machine. We can do this by running the command npm install -g sails
in our terminal. Once installed, we can create a new Sails application by running sails new my-sails-api
and then cd
into the newly created directory.
Project Structure
The Sails.js framework provides a default project structure that includes directories for controllers, models, policies, and more. We’ll focus on the api
directory, where we’ll define our API endpoints.
Creating Our First Endpoint
Let’s create our first endpoint by defining a route in the routes.js
file. We’ll add the following code to create a route for the /
endpoint:
'GET /': 'HomeController.index'
Next, we’ll create the HomeController
and its index
action. We can do this by running sails generate controller home
and then adding the following code to the index
action:
module.exports = {
index: async function(req, res) {
return res.json({ message: 'Welcome to our API!' });
}
};
Building the User Management Endpoints
Now that we have our first endpoint up and running, let’s build the user management endpoints. We’ll start by creating a User
model using the sails generate model user
command. We’ll then define the attributes for the User
model, including fullName
, email
, password
, and more.
Next, we’ll create the registration endpoint by defining a route in the routes.js
file:
'POST /user/register': 'UserController.register'
We’ll then create the register
action in the UserController
and add the necessary logic to create a new user record and send a confirmation email.
Implementing Login and Password Reset
To implement the login feature, we’ll create a login
action in the UserController
and add the necessary logic to authenticate the user and return a JSON Web Token (JWT). We’ll also create a forgotPassword
action to handle password reset requests.
Deployment to Heroku
Finally, we’ll deploy our API to Heroku by creating a new Heroku app and adding the necessary environment variables. We’ll also need to configure our database settings and add the Heroku PostgreSQL add-on.
- Create a new Heroku app: https://heroku.com/new
- Add environment variables:
heroku config:set SAILS_ENV=production
- Configure database settings:
heroku addons:create heroku-postgresql:hobby-dev
With these steps, we’ve successfully built and deployed a production-ready Node.js web API using Sails.js.