If you are evaluating how to start using NodeJS instead of Laravel for your next project, or you are just trying to migrate your website made with Laravel to NodeJS, this post is for you.
Learn what the alternatives to each Laravel framework feature in the NodeJS ecosystem are.
Frameworks
Unlike PHP, which counts with many popular frameworks such as Laravel, Symfony, etc.; In the NodeJS world, developers like more freedom. They use minimalist frameworks like "express
" to manage their routes and middleware. All the rest is up to them, adding the packages they need for the specific project they are working on.
The popular frameworks for NodeJS are:
- Express
Recommended
https://expressjs.com
- Nest https://nestjs.com
- Salis https://sailsjs.com
Express example app:
import express from 'express';
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.get('/users', (req, res) => {
res.json([{ username: 'Rodrigo' }, { username: 'Julio' }]);
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
Mailing
The way of sending emails from NodeJS apps is to use one of the NPM packages from an email service; most of them have their NodeJS version.
Tip: I recommend to create your own wrapper and avoid using the packages directly. It will provide you flexibility in the future to switch services.
Popular email service packages:
Mailing example implementation:
// ---------------------
// mail.js
// ---------------------
import mailgun from 'mailgun-js';
const MAILGUN_KEY = 'XXXXXXXXXXXXXXXXXXXXXXX';
const MAILGUN_DOMAIN = 'www.mydomain.com';
const mailgun = mailgun({apiKey: MAILGUN_KEY, domain: MAILGUN_DOMAIN});
const mail = {
send: (options={}) => {
const defaultOptions = {
from: 'Excited User <me@samples.mailgun.org>',
to: 'serobnic@mail.ru',
};
mailgun.messages().send({...defaultOptions, ...options} , function (error, body) {
console.log(body);
});
}
};
export default mail;
// ---------------------
// CreateUser.js
// ---------------------
import mail from './utils/mail';
function CreateUser(data){
// ...
mail.send({
subject: "Welcome to ServiceName",
body: "..."
});
}
Validations
When it comes to validations, my favorite NPM package is Yup
, the way of doing the validations is different from Laravel, but it's very powerful and flexible.
Packages:
- Yup
recommended
https://www.npmjs.com/package/yup
Yup example:
import * as yup from 'yup';
// create a validation schema
const schema = yup.object().shape({
name: yup.string().required(),
age: yup.number().required().positive().integer(),
email: yup.string().email(),
});
// validate your data with the schema
try {
schema.isValidSync(data);
}catch(err){
console.log(err);
}
ORM
There are many ORMs solutions for NodeJS; most of them have similar APIs. I will list here the most popular libraries and my recommendation.
- Knex
recommended
(query builder) https://www.npmjs.com/package/knex
- TypeORM (for typescript) https://www.npmjs.com/package/typeorm
Translations
In the case of translations, you can opt for a robust library or create your own. Some packages could be complicated to set up and may require additional packages to make them work. In the case of simple projects, try using a simples solution.
Popular packages are:
- i18next https://www.i18next.com/
- Lingui https://lingui.js.org/
Queue
When it comes to Job/Tasks queue for Node.JS, I only have experience with one library. It's very popular and simple to implement.
- Bee-Queue https://github.com/bee-queue/bee-queue
Example:
import Queue from 'bee-queue';
const queueConfig = {
getEvents: false,
isWorker: false,
// ...
}
// init Queue
const emailQueue = new Queue('EMAIL_DELIVERY', queueConfig);
// add Job to Queue
emailQueue.createJob({template:"welcome", userId: 1}).save();
// process Job
emailQueue.process( async (job) => {
console.log(`Sending ${job.data.template} to UserId ${job.data.userId}`);
return mail.send(...);
});
Image manipulation
There are a few ways to implement image manipulations on your application. My recommendation would be to rely on a service that handles all the complicated processes for you.
In case you need to implement this on your own, please take a look at the following recommendations
Services
- AWS Serverless Image Handler https://aws.amazon.com/solutions/implementations/serverless-image-handler/ Upload your pictures to your S3 bucket and use a serverless function to generate the sizes automatically. This option also provides a CDN.
- Cloudinary https://cloudinary.com/ Free for small projects and with an integrated CDN.
Packages
import sharp from 'sharp';
sharp('input.jpg')
.rotate()
.resize(200)
.toBuffer()
.then( data => { ... })
.catch( err => { ... });
Authentication
Authentication is a big topic with many security implications. Normally you will create NodeJS APIs that will relay on sessions or tokens. You could use a package or create a custom middleware to handle the authentication.
Popular services and packages:
- Auth0 https://auth0.com/
- JSON Web Token https://www.npmjs.com/package/jsonwebtoken
Testing
About testing Node.JS application, I have only one option to recommend you. jest
It's very powerful, and you can find many tutorials and examples on the internet.
- Jest https://jestjs.io/
API
This one is one of my favorites topics and one reason for moving to the Node.JS world. Using express, you can create REST endpoints very quickly. Or implement a GraphQL server with the help of Apollo.
REST
- Express https://expressjs.com/
GraphQL
Middlewares
With the help of express or a similar framework. Creating middleware for your application is very simple.
import express from 'express';
const app = express();
app.use( (req, res, next) => {
console.log('Request URL:', req.originalUrl);
if(!req.session.username)
{
res.redirect('/login');
}
next();
});
// ...
more info about middleware with express https://expressjs.com/en/guide/using-middleware.html
Conclusion
You will find many packages to do similar stuff like Laravel. Pick the one that is just right for your current project. Consider the Github repository's stars and how easy it is to implement.