Sails.js – Sailing Through MVC with Node.js
Master the MVC architecture with Sails.js. Learn how to set up Sails, leverage its real-time features, and find contribution opportunities to help improve the framework.
Lesson Overview
Get ready to dive into Sails.js, a powerful MVC (Model-View-Controller) framework designed for building real-time apps. If you’ve ever worked with Express, you might find Sails.js to be its feature-packed cousin, bringing in a lot of tools to help you build large-scale applications quickly. But while it’s got some muscle under the hood, Sails.js is not as widely used as Express or Nest, so there’s plenty of room for you to contribute and make a real impact.
In this tutorial, we’ll explore:
- Sails.js 101: What Sails is all about, why it uses MVC, and why it’s a great framework for real-time apps.
- Getting Comfortable with Sails.js: How to install it, set up your first project, and get it running—without any headaches.
- Real-Time Magic with Sails.js: One of the coolest things about Sails is how easily it handles real-time communication, especially with WebSockets. We’ll show you how this works and how you can contribute in this space.
- Finding Your Contribution Zone in Sails.js: Where to focus your efforts as a contributor, whether you want to fix bugs, improve documentation, or add new features. Sails is a great project for getting your feet wet in open-source contribution.
By the end of this lesson, you’ll not only have a solid understanding of Sails.js, but you’ll also be ready to jump in and contribute to the project—especially in areas like real-time features, which are in high demand.
Sails.js 101 – What Is It and Why Should You Care?
Let’s start with the basics: what exactly is Sails.js, and why should you care about it?
At its core, Sails.js is a Node.js framework that’s built with the MVC architecture in mind. If you’ve never worked with MVC before, don’t worry—it’s not as complicated as it sounds. The idea is to break your app into three distinct parts:
- Model: Represents the data and business logic of the app.
- View: The part of the app that the user sees (HTML, templates, etc.).
- Controller: The glue that holds everything together, handling requests, pulling data from the model, and rendering it in the view.
So why use MVC? It makes complex apps easier to manage. Instead of writing one huge chunk of code that does everything, MVC helps you keep things organized and modular. And when you’re building large apps (especially real-time ones), this kind of organization is a lifesaver.
Why Sails.js?
Here are some reasons Sails.js is worth your attention:
- Real-Time Power: Sails is designed with real-time apps in mind, which means it has built-in support for WebSockets and other technologies that make live updates possible.
- Auto-Generated API: With Sails, you get an auto-generated RESTful API out of the box. That means you don’t have to write a bunch of boilerplate code to handle things like creating, reading, updating, and deleting data. Sails does it for you!
- Built for Scale: Sails is designed to handle big apps with lots of moving parts. Whether you're building a social media platform, a chat app, or any other real-time application, Sails gives you the tools to do it.
- MVC Architecture: Sails follows the tried-and-true MVC pattern, which makes your code cleaner and easier to manage as your app grows.
- Community and Ecosystem: While not as large as Express, Sails has a dedicated community and a growing ecosystem of plugins and tools.
If you’ve ever thought about building a real-time app like a chat platform, multiplayer game, or live collaboration tool, Sails.js is a framework worth considering. And the best part? Because it’s not as popular as Express or Nest, there are tons of opportunities for you to contribute and stand out!
Getting Comfortable with Sails.js
Now that you’ve got an idea of what Sails.js is and why it’s worth your time, let’s roll up our sleeves and get Sails installed on your machine. Setting up Sails is pretty straightforward, even if you’ve never worked with an MVC framework before.
Step 1: Install Sails.js
The first thing you’ll need is Node.js, which you probably already have if you’ve been working with other frameworks like Next.js. If not, head over to nodejs.org and download the latest version.
With Node.js installed, installing Sails is just a matter of running a single command. Open your terminal (or command prompt) and run:
npm install sails -g
The -g
flag installs Sails globally on your system, so you can use the sails
command from anywhere.
Step 2: Create a New Sails Project
Now that you’ve got Sails installed, let’s create a new project. In your terminal, navigate to the directory where you want your project to live, and run the following command:
sails new myFirstSailsApp
This will create a new Sails project with all the basic files and folders you need to get started. Sails gives you a bit of structure right out of the gate, which is super helpful when you’re building bigger apps.
Step 3: Run Your Sails App
To run your new Sails app, navigate into the project folder:
cd myFirstSailsApp
Then start the development server by running:
sails lift
That’s it! You’ve got a running Sails app. Open your browser and go to http://localhost:1337
, and you should see the default Sails welcome page. Congrats, you’re up and running with Sails!
Step 4: Explore the Sails File Structure
Before we dive deeper into Sails, it’s important to get comfortable with the structure of a typical Sails app. Here’s a quick breakdown of the key directories and files you’ll find in your new project:
- api/: This is where your app’s logic lives. Inside, you’ll find folders for controllers, models, and services.
- config/: This folder holds configuration files for your app, such as database settings and routes.
- views/: This is where you’ll store your HTML or template files for rendering views.
Sails makes it easy to keep everything organized, so as your app grows, you won’t have a tangled mess of code to deal with.
Real-Time Magic with Sails.js
One of Sails.js’s standout features is how effortlessly it handles real-time communication. If you’re building apps where live updates are a core feature (like chat apps, live dashboards, or multiplayer games), Sails makes your life a lot easier.
WebSockets 101
At the heart of Sails’ real-time capabilities is WebSockets. If you’re not familiar with WebSockets, here’s a quick breakdown: they’re a communication protocol that allows you to open a two-way communication channel between a client and a server. Unlike traditional HTTP, where the client requests something and the server responds, WebSockets allow both the client and server to send messages back and forth in real time.
Sails uses Socket.io under the hood to handle WebSocket connections, which means that once you’ve got your Sails app up and running, adding real-time functionality is a breeze.
Adding Real-Time Features to Your Sails App
Let’s add a simple real-time feature to your Sails app. In this example, we’ll create a chat room where users can send and receive messages in real time.
First, we’ll create a new ChatController to handle our chat functionality.
-
Create a new controller: In your terminal, run the following command:
sails generate controller chat
This will create a new file in
api/controllers/ChatController.js
. Open this file, and add the following code:module.exports = { sendMessage: function(req, res) { var message = req.body.message; // Broadcast the message to all connected clients sails.sockets.broadcast('chatroom', 'newMessage', { message: message }); return res.json({ status: 'Message sent!' }); } };
-
Set up a WebSocket connection: Now, let’s set up the client-side code to handle WebSocket connections. In your
views/layout.ejs
file, add the following script tags inside the<body>
tag:<script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect(); socket.on('connect', function() { console.log('Connected to WebSocket'); }); // Listen for new messages socket.on('newMessage', function(data) { var messageList = document.getElementById('messages'); var newMessage = document.createElement('li'); newMessage.textContent = data.message; messageList.appendChild(newMessage); }); </script>
This will establish a WebSocket connection between the client and the server and listen for incoming messages.
-
Create a chat view: Now, let’s create a simple view where users can send and receive messages. Open
views/chat.ejs
and add the following code:<h1>Chat Room</h1> <ul id="messages"></ul> <form action="/chat/sendMessage" method="POST"> <input type="text" name="message" placeholder="Enter your message"> <button type="submit">Send</button> </form>
-
Test it out: Start your Sails app (
sails lift
), open your browser, and go tohttp://localhost:1337/chat
. Open the page in multiple tabs, and try sending messages. You should see the messages appear in real time across all open tabs!
Congratulations—you’ve just built a simple real-time chat room with Sails.js! Now you’re ready to explore more advanced real-time features and maybe even contribute to improving this area of the framework.
Finding Your Contribution Zone in Sails.js
So, where should you start contributing to Sails.js? Here are some ideas:
- Real-Time Features – As we’ve seen, real-time communication is one of Sails’ strengths. You could contribute by improving WebSocket support, fixing bugs related to real-time features, or even adding new capabilities.
- Bug Fixes – Like any open-source project, Sails has its fair share of bugs. Check out the GitHub repo for issues labeled “good first issue.”
- Improving Documentation – Sails’ docs are solid, but there’s always room for improvement. If you find an area that could use more clarity, consider submitting a pull request to improve it.
- Adding Features – If you’re feeling ambitious, you could contribute by adding new features or improving existing ones. Just make sure to discuss any major changes with the maintainers first.
- Writing Tests – Tests are critical for ensuring that new features don’t break existing code. If you notice a gap in test coverage, writing tests is a great way to contribute.
End of Lesson Task: Find a Real-Time Issue in Sails.js and Submit a Pull Request
Your task for this lesson is to head over to the Sails.js GitHub repo and find an issue related to real-time features. Once you find one, submit a pull request that addresses the issue. It could be a bug fix, a feature enhancement, or an improvement to the documentation. The key is to get hands-on experience with contributing to Sails.js.