Date:

You Probably Don’t Know How to Write APIs Like This Using Express

Discovering a Different Approach in n8n

The Raw Server.ts File: A Custom Express Setup

The heart of n8n’s backend lies in its Server class, which extends an AbstractServer and sets up an Express-based API. This isn’t just a simple Express app with some routes slapped onto it. Instead, it dynamically loads controllers, handles webhooks, and uses middleware to configure the API.

No Traditional Route Files – Just Decorators

n8n ditches the typical route files and instead relies on TypeScript decorators for defining API endpoints. This is where it starts to feel very NestJS-like. Check out route.ts:

import type { RequestHandler } from 'express';
import { getRouteMetadata } from './controller.registry';
import type { Controller, Method, RateLimit } from './types';

const RouteFactory = (method: Method) => ({
  path: `/${string}`,
  options: RouteOptions = {},
): MethodDecorator => ({
  target,
  handlerName,
}) => ({
  routeMetadata: getRouteMetadata(target.constructor as Controller, handlerName),
  method,
  path,
});

The Decorators: A Different Way to Define APIs

This makes it easy to swap out implementations, mock dependencies in tests, and keep the code modular.

Final Thoughts

If you’re coming from a standard Express.js background, n8n’s API structure might feel alien at first. But once you get past the initial "where are the routes?" confusion, you’ll understand how decorators handle routing, authentication, and middleware injection, it starts to make a lot of sense.

Conclusion

By using decorators and dependency injection, n8n manages to keep its API modular, maintainable, and easy to extend. So, the next time you’re building an Express backend, maybe try throwing in some decorators. Who knows? You might just like it.

FAQs

Q: What is n8n?
A: n8n is a Node.js backend framework that uses TypeScript decorators for defining API endpoints.

Q: What is the benefit of using decorators in n8n?
A: Decorators help to keep the code modular, maintainable, and easy to extend.

Q: How does n8n handle routing and authentication?
A: n8n uses decorators to handle routing and authentication, making it easy to swap out implementations and mock dependencies in tests.

Q: What is the difference between n8n and traditional Express.js?
A: n8n uses TypeScript decorators for defining API endpoints, whereas traditional Express.js uses traditional route files.

Latest stories

Read More

LEAVE A REPLY

Please enter your comment!
Please enter your name here