AdonisJS the Laravel Alternative for Node.js?

itsimiro
6 min readNov 28, 2024

--

Laravel stands out as the framework of choice for many developers because of its simplicity, rapid deployment capabilities, and extensive out-of-the-box solutions. Its elegance and efficiency make it a favorite for building everything from small projects to large-scale applications.

But what if I told you that the Node.js ecosystem has its contender — a framework that can rival Laravel regarding convenience, developer experience, and deployment speed? Enter AdonisJS, a Node.js framework inspired by Laravel, designed to bring that same level of simplicity and power to JavaScript.

Laravel: The Gold Standard in PHP

Laravel has revolutionized PHP development. It’s known for:

Ease of Use: With intuitive syntax and powerful tools like Eloquent ORM, Laravel simplifies complex tasks.

Rich Ecosystem: From Blade templating to first-party packages like Passport and Sanctum, Laravel covers nearly every use case.

Developer-Friendly Features: Built-in authentication, robust routing, task scheduling, and easy database migrations are just a few reasons developers adore it.

Massive Community Support: Laravel’s active community ensures you’ll always find solutions, tutorials, and third-party packages for your needs.

AdonisJS: Laravel analog in Node.js

AdonisJS is like Laravel’s sibling, but in the JavaScript world. It brings the familiar structure and philosophy of Laravel to Node.js, making it an attractive choice for developers already comfortable with JavaScript.

Why AdonisJS Stands Out

Familiar Development Experience: If you’ve used Laravel, working with AdonisJS will feel like second nature. Concepts like service providers, middleware, and dependency injection are implemented similarly, offering a seamless transition.

JavaScript Everywhere: With AdonisJS, you can build full-stack JavaScript applications, from frontend to backend, without switching languages.

Built-in Real-Time Features: AdonisJS natively supports WebSockets, making it an excellent choice for applications requiring real-time updates, like chat apps or live notifications.

Modern JavaScript: AdonisJS leverages the power of ES6+ and integrates seamlessly with TypeScript, giving you access to modern programming features out of the box.

Laravel vs. AdonisJS: A Head-to-Head Comparison

Installation

Just like in Laravel, AdonisJS allows you to customize your installation paths. You can choose between setting up a web-based application or an API. You can configure the database you need or even start from your own custom template!

If you need authentication and authorization similar to Laravel Sanctum or Laravel Passport, AdonisJS has you covered with built-in solutions!

If you want to create a project with a starter set of APIs and access tokens, just write a command:

npm init adonisjs@latest hello-world -- --kit=api --auth-guard=access_tokens

Folder structure

AdonisJS offers a well-structured folder system that makes your project easy to navigate and refactor. However, if the default setup doesn’t suit your needs, you have the flexibility to customize it to your preferences!

{
"imports": {
"#controllers/*": "./app/controllers/*.js",
"#exceptions/*": "./app/exceptions/*.js",
"#models/*": "./app/models/*.js",
"#mails/*": "./app/mails/*.js",
"#services/*": "./app/services/*.js",
"#listeners/*": "./app/listeners/*.js",
"#events/*": "./app/events/*.js",
"#middleware/*": "./app/middleware/*.js",
"#validators/*": "./app/validators/*.js",
"#providers/*": "./app/providers/*.js",
"#policies/*": "./app/policies/*.js",
"#abilities/*": "./app/abilities/*.js",
"#database/*": "./database/*.js",
"#tests/*": "./tests/*.js",
"#start/*": "./start/*.js",
"#config/*": "./config/*.js"
}
}

What’s included?

Just like Laravel, AdonisJS streamlines development by providing a comprehensive set of built-in features to handle the core aspects of web applications, eliminating the need for extensive configuration or third-party dependencies. Here’s a breakdown of what AdonisJS offers:

Routing: Effortlessly define routes for your application with clean and intuitive syntax. AdonisJS supports RESTful and WebSocket routes, catering to both traditional and real-time applications.

import router from '@adonisjs/core/services/router'

router.get('/', () => {
return 'Hello world from the home page.'
})

router.get('/about', () => {
return 'This is the about page.'
})

router.get('/posts/:id', ({ params }) => {
return `This is post with id ${params.id}`
})

Controllers: Keep your business logic organized by separating it into controller classes, a structure familiar to Laravel developers.

export default class UsersController {
index() {
return [
{
id: 1,
username: 'virk',
},
{
id: 2,
username: 'romain',
},
]
}
}

Middleware: Handle tasks like authentication, logging, or request transformation using middleware. AdonisJS provides a robust middleware pipeline similar to Laravel’s.

import router from '@adonisjs/core/services/router'

router.use([
() => import('@adonisjs/core/bodyparser_middleware')
])

Requests and Responses: Work with HTTP requests and responses elegantly. AdonisJS provides a simple API to manage headers, cookies, file uploads, and more.

import router from '@adonisjs/core/services/router'

router.get('posts/:slug/comments/:id', async ({ request }) => {
/*
* URL: /posts/hello-world/comments/2
* params: { slug: 'hello-world', id: '2' }
*/
request.params()
})
import router from '@adonisjs/core/services/router'

router.get('/', async ({ response }) => {
/** Plain string */
response.send('This is the homepage')

/** Html fragment */
response.send('<p> This is the homepage </p>')

/** JSON response */
response.send({ page: 'home' })

/** Converted to ISO string */
response.send(new Date())
})

Validation: AdonisJS has a built-in validation system to ensure data integrity. Define validation rules directly in your controllers or middleware, much like Laravel’s request validation.

import vine from '@vinejs/vine'

/**
* Validates the post's creation action
*/
export const createPostValidator = vine.compile(
vine.object({
title: vine.string().trim().minLength(6),
slug: vine.string().trim(),
description: vine.string().trim().escape()
})
)

/**
* Validates the post's update action
*/
export const updatePostValidator = vine.compile(
vine.object({
title: vine.string().trim().minLength(6),
description: vine.string().trim().escape()
})
)

Session Management: Easily manage user sessions with AdonisJS. It supports session storage in memory, files, Redis, or databases, giving you flexibility in how sessions are handled.

Exception Handling: AdonisJS includes a robust exception-handling mechanism, allowing you to define custom error responses or manage global exceptions efficiently.

export default class HttpExceptionHandler extends ExceptionHandler {
protected debug = !app.inProduction
protected renderStatusPages = app.inProduction

async handle(error: unknown, ctx: HttpContext) {
return super.handle(error, ctx)
}

async report(error: unknown, ctx: HttpContext) {
return super.report(error, ctx)
}
}

Static File Server: Serve static assets like images, CSS, and JavaScript files seamlessly, with options for caching and optimization.

import { defineConfig } from '@adonisjs/static'

const staticServerConfig = defineConfig({
enabled: true,
etag: true,
lastModified: true,
dotFiles: 'ignore',
})

export default staticServerConfig

ORM Support: AdonisJS offers excellent ORM capabilities with Lucid, a feature-rich ORM inspired by Laravel’s Eloquent. It also integrates with other popular ORMs like Prisma, Drizzle, and TypeORM, giving developers the freedom to choose.

Redis Support: AdonisJS natively supports Redis for caching, session storage, and other real-time functionalities, making it ideal for high-performance applications.

Templates and SSR: Use built-in template engines for server-side rendering (SSR) or integrate seamlessly with frontend frameworks for a modern development workflow.

Testing in AdonisJS

AdonisJS comes with its test runner specifically designed to work with the framework ecosystem. It is tightly integrated with the application lifecycle, making it easy to write and execute tests without the need for external test runners such as Jest or Mocha (although you can use them too if preferred).

Deployment

AdonisJS is designed to simplify the development process, but it also provides flexibility and control when deploying applications. Whether you host applications on traditional servers, cloud platforms, or in containerized environments, AdonisJS can be deployed efficiently.

I will describe a couple of steps to deploy your application and you will see how easy it is!

Set Environment Variables: Use .env files to manage sensitive configurations like database credentials, API keys, and application secrets.

Build the Application: Compile the project into JavaScript.

node ace build --production

Optimize for Production: Run the optimization command to precompile the container and improve performance.

node ace optimize

Choosing a Hosting Environment: Use services like DigitalOcean, Linode, or AWS EC2 to host your application. AdonisJS works easily with cloud platforms such as Heroku or AWS Elastic Beanstalk.

AdonisJS applications can be containerized using Docker, making them portable and easy to deploy on platforms like Kubernetes or AWS ECS.

Benchmark

Here’s a video that demonstrates how and why AdonisJS with Node.js outperforms Laravel with PHP in various scenarios.

Laravel vs. AdonisJS: A Head-to-Head Comparison

| Feature        | Laravel                              | AdonisJS                              |
|----------------|--------------------------------------|---------------------------------------|
| Language | PHP | JavaScript |
| Performance | Good, optimized for PHP-based apps | Excellent, thanks to Node.js's non-blocking I/O |
| Ease of Learning | Beginner-friendly, extensive resources | Slightly steeper curve, smaller community |
| Real-Time | Support Requires external tools (e.g., Pusher) | Built-in WebSocket support |
| Community | Large and active | Growing but smaller |
| Ecosystem | Mature, vast | Developing but promising |

When to Choose Laravel

  • Your team is proficient in PHP.
  • You need a framework with a large ecosystem and community.
  • You’re building server-rendered applications, APIs, or monolithic apps.

When to Choose AdonisJS

  • Your team is skilled in JavaScript or TypeScript.
  • You’re building real-time apps, SPAs, or microservices.
  • You want a uniform JavaScript codebase for both frontend and backend.

Conclusion

While Laravel remains a strong force in PHP development, AdonisJS is proving to be a formidable contender in the Node.js ecosystem. It combines the simplicity and developer-centricity of Laravel with the power of modern JavaScript, offering a robust solution for JavaScript enthusiasts.

If you’re already in the Laravel camp but want to explore the world of JavaScript, AdonisJS could be the Laravel solution you’ve been looking for.

--

--

itsimiro
itsimiro

Written by itsimiro

Passionate developer exploring the realms of software engineering. Writing about tech, coding adventures, and everything in between!

Responses (2)