Django's pitch has always been the batteries. You start a project and you already have an ORM, migrations, users, sessions, permissions, forms, email, file storage, translations, caching and an admin. Add Django REST Framework and Celery, and a team can build a B2B product without assembling anything.

So when a Django team has to build something in TypeScript (a backend next to a frontend that's already TypeScript, a team that wants one language, a company that standardized on Node), the first question is usually "is there a Django for Node.js?". For a long time the honest answer was "not really": Express and a pile of libraries you pick yourself.

Nest is the closest thing to a yes. It gives a backend one structure (modules, dependency injection, controllers, validation, guards), and its first-party packages now cover most of Django's batteries: sign-in and sessions, permissions, email, file storage, translations, background jobs, scheduling, caching, rate limiting and configuration. It doesn't cover all of them, and I'll say plainly which ones are missing, starting with the admin.

This post is the tour I'd give a Django team on day one: the tools, the structure, each Django battery and its Nest counterpart with code on both sides, how it ships, and the differences that will actually bite.

The short version

Django Nest
startproject, startapp, runserver nest new, nest g resource, npm run start:dev
Apps and INSTALLED_APPS modules and their imports
Models, makemigrations, migrate Drizzle or TypeORM, and their migration tools
Views, DRF viewsets, urls.py controllers with route decorators
Forms, DRF serializers a validation pipe, with Zod or class-validator
Middleware middleware, guards and interceptors
django.contrib.auth, sessions @nestjs/authentication
Permissions, DRF permission classes @nestjs/authorization policies
settings.py @nestjs/config
send_mail() @nestjs/mail
default_storage, django-storages @nestjs/storage
gettext, .po files @nestjs/i18n
Celery, Celery beat @nestjs/bullmq, @nestjs/schedule
Signals, transaction.on_commit() @nestjs/event-emitter, @nestjs/outbox
The cache framework, DRF throttling @nestjs/cache-manager, @nestjs/throttler
Management commands, manage.py shell standalone scripts, the REPL
TestCase, APIClient @nestjs/testing with Supertest
drf-spectacular @nestjs/swagger
Channels gateways
The admin nothing first-party

Every row has its own section below. The docs have the same mapping as a reference page, with a link to the full chapter for each row: Coming from Django.

Your tools, translated

Before any code, here's what replaces the things around it:

Django world Nest world
Python Node.js (a current LTS release) and TypeScript
pip, requirements.txt or pyproject.toml npm, package.json
PyPI the npm registry
A virtualenv node_modules, per project, with nothing to activate
django-admin startproject npx @nestjs/cli new
manage.py runserver npm run start:dev, which restarts on every save
manage.py startapp nest generate resource
manage.py test, pytest npm test, with Vitest
mypy the TypeScript compiler, on every build
Black, Ruff Prettier and oxlint, set up by nest new
Gunicorn or uWSGI Node.js itself: node dist/main.js

npm run start:debug starts the app with the Node inspector attached, and VS Code or WebStorm connects to it the way PyCharm attaches to a Django process.

Project layout

nest new orders-api gives you a small src/ folder. As the app grows, the convention is one folder per feature, like a Django app, each with its module, and tests next to the code they test:

src/ main.ts # what runserver and wsgi.py do app.module.ts # the root module: your INSTALLED_APPS database/ schema.ts # tables, if you use Drizzle orders/ orders.module.ts orders.controller.ts # views.py and urls.py orders.controller.spec.ts orders.service.ts # services.py, or your fat model's methods orders.repository.ts # the queries create-order.schema.ts # serializers.py payments/ payments.module.ts ... test/ drizzle/ # generated migrations 

Apps become modules

A Django project lists its apps in INSTALLED_APPS, and Django finds their models, URLs, templates and admin classes by convention. A Nest application is a tree of modules, and each one lists what it contains:

// orders/orders.module.ts import { Module } from '@nestjs/common'; import { OrdersController } from './orders.controller.js'; import { OrdersRepository } from './orders.repository.js'; import { OrdersService } from './orders.service.js'; @Module({ controllers: [OrdersController], providers: [OrdersService, OrdersRepository], exports: [OrdersService], }) export class OrdersModule {} 

The root module imports the feature modules, which is what INSTALLED_APPS does:

// app.module.ts import { Module } from '@nestjs/common'; import { OrdersModule } from './orders/orders.module.js'; import { PaymentsModule } from './payments/payments.module.js'; @Module({ imports: [OrdersModule, PaymentsModule], }) export class AppModule {} 

Nothing is discovered. A controller that isn't listed serves no routes. That feels like ceremony for about a week, and then it's the thing you like: what the app does at startup is written down in its modules.

Modules are also a boundary that Django apps don't have. Any Django app can import any other app's models. In Nest, a provider is visible only inside its own module, unless the module exports it and another module imports the module. On a big codebase, that's what stops "payments" from quietly reaching into "orders".

Services and dependency injection

Django has no dependency injection: a view imports the models and functions it needs. Nest code lives in providers, classes marked @Injectable(), and Nest creates them and passes them to the constructors that ask for them:

// orders/orders.service.ts import { Injectable } from '@nestjs/common'; import { Mailer } from '@nestjs/mail'; import { OrdersRepository } from './orders.repository.js'; @Injectable() export class OrdersService { constructor( private readonly ordersRepository: OrdersRepository, private readonly mailer: Mailer, ) {} } 

private readonly in the constructor declares and assigns the field in one step. The business logic a Django project keeps in fat models or a services.py goes in providers like this one, and a test replaces the repository or the mailer by passing another one in, with no mock.patch on import paths.

Models and migrations

Here's the first real difference: Nest has no ORM of its own. Its first-party integrations are Drizzle, where the schema is TypeScript and queries read like SQL, and TypeORM, where models are decorated classes and feel closer to Django's. Prisma and MikroORM work too. I'll use Drizzle here, because its migrations work the way makemigrations does.

A Django model:

# orders/models.py class Order(models.Model): class Status(models.TextChoices): PENDING = "pending" PAID = "paid" SHIPPED = "shipped" customer = models.ForeignKey(Customer, on_delete=models.CASCADE) status = models.CharField( max_length=16, choices=Status.choices, default=Status.PENDING ) total_cents = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) 

The same table with Drizzle, where the row type is inferred from the table:

// database/schema.ts (customers is declared in this file too) import { integer, pgEnum, pgTable, timestamp, uuid } from 'drizzle-orm/pg-core'; export const orderStatus = pgEnum('order_status', [ 'pending', 'paid', 'shipped', ]); export const orders = pgTable('orders', { id: uuid().primaryKey().defaultRandom(), customerId: uuid('customer_id') .notNull() .references(() => customers.id, { onDelete: 'cascade' }), status: orderStatus().notNull().default('pending'), totalCents: integer('total_cents').notNull(), createdAt: timestamp('created_at').notNull().defaultNow(), }); export type Order = typeof orders.$inferSelect; 

makemigrations becomes npx drizzle-kit generate, which writes SQL migration files from the changes to the schema, and migrate becomes npx drizzle-kit migrate. With TypeORM, migration:generate and migration:run do the same job.

Queries go through the injected database. Order.objects.filter(customer_id=..., status="pending").order_by("-created_at") becomes:

// orders/orders.repository.ts import { Injectable } from '@nestjs/common'; import { InjectDrizzle } from '@nestjs/drizzle'; import { and, desc, eq } from 'drizzle-orm'; import type { NodePgDatabase } from 'drizzle-orm/node-postgres'; import { orders } from '../database/schema.js'; @Injectable() export class OrdersRepository { constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {} findPending(customerId: string) { return this.db .select() .from(orders) .where( and(eq(orders.customerId, customerId), eq(orders.status, 'pending')), ) .orderBy(desc(orders.createdAt)); } } 

A query runs when it's awaited. There's no lazy QuerySet that a template evaluates later, so nothing hits the database by accident, and an N+1 shows up in your own code, where you can see it. Load related rows with a join or Drizzle's relational queries, as select_related() and prefetch_related() do.

transaction.atomic() becomes a callback, whose queries commit when it resolves and roll back when it throws:

async place(customerId: string, items: NewOrderItem[]) { return this.db.transaction(async (tx) => { const [order] = await tx .insert(orders) .values({ customerId, totalCents: sumOf(items) }) .returning(); await tx .insert(orderItems) .values(items.map((item) => ({ ...item, orderId: order.id }))); return order; }); } 

Queries in the transaction go through tx, not through the injected database. That's the one mistake everybody makes once.

Views and URLs become controllers

A DRF viewset and its router:

# orders/views.py class OrderViewSet(viewsets.ModelViewSet): serializer_class = OrderSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return Order.objects.filter(customer=self.request.user.customer) # urls.py router = DefaultRouter() router.register("orders", OrderViewSet, basename="order") urlpatterns = [path("api/", include(router.urls))] 

In Nest, a controller declares its routes with decorators, so there's no urls.py:

// orders/orders.controller.ts import { Body, Controller, Delete, Get, HttpCode, Param, ParseUUIDPipe, Post, } from '@nestjs/common'; import { CurrentUser } from '@nestjs/authentication'; import type { User } from '../users/user.js'; import { createOrderSchema, type CreateOrderDto, } from './create-order.schema.js'; import { OrdersService } from './orders.service.js'; @Controller('orders') export class OrdersController { constructor(private readonly ordersService: OrdersService) {} @Get() findAll(@CurrentUser() user: User) { return this.ordersService.findForCustomer(user.id); } @Get(':id') findOne(@CurrentUser() user: User, @Param('id', ParseUUIDPipe) id: string) { return this.ordersService.findOne(user, id); } @Post() create( @CurrentUser() user: User, @Body({ schema: createOrderSchema }) dto: CreateOrderDto, ) { return this.ordersService.place(user, dto); } @Delete(':id') @HttpCode(204) cancel(@CurrentUser() user: User, @Param('id', ParseUUIDPipe) id: string) { return this.ordersService.cancel(user, id); } } 

What to notice, coming from DRF:

  • @Controller('orders') is the URL prefix, and each method decorator adds a path. app.setGlobalPrefix('api') adds the api/ from urls.py.
  • Route parameters arrive as strings. ParseUUIDPipe or ParseIntPipe converts and checks one, like a path converter.
  • A POST answers 201 by default and everything else 200. @HttpCode() changes it.
  • A handler returns the body, and Nest serializes it as JSON. get_object_or_404() becomes throw new NotFoundException() in the service.
  • There's no IsAuthenticated above, and it isn't missing: with @nestjs/authentication, every route requires a signed-in user unless it's marked @Public().

There are no generic viewsets. The five methods above are the whole of a ModelViewSet, written out, and nest g resource writes that boilerplate for you. I'd argue it's a fair trade: a new developer reads one file and knows every route.

Serializers become schemas

A DRF serializer validates input and shapes output. In Nest those are two separate jobs.

Input is validated before the handler runs, by a pipe. Here's a DRF serializer:

# orders/serializers.py class OrderItemSerializer(serializers.Serializer): product_id = serializers.UUIDField() quantity = serializers.IntegerField(min_value=1, max_value=20) class CreateOrderSerializer(serializers.Serializer): items = OrderItemSerializer(many=True, allow_empty=False) note = serializers.CharField(max_length=500, required=False) 

The same rules as a Zod schema, which also gives the DTO its type:

// orders/create-order.schema.ts import { z } from 'zod'; export const createOrderSchema = z.object({ items: z .array( z.object({ productId: z.uuid(), quantity: z.int().min(1).max(20), }), ) .min(1), note: z.string().max(500).optional(), }); export type CreateOrderDto = z.infer<typeof createOrderSchema>; 

The controller above passes it with @Body({ schema: createOrderSchema }), and one line in main.ts turns validation on for the whole app:

app.useGlobalPipes(new StandardSchemaValidationPipe()); 

An invalid body gets a 400 that lists every failed rule, like is_valid(raise_exception=True). Valibot and ArkType work the same way, and if you'd rather have a declarative class, class-validator DTOs with ValidationPipe are the closest thing to a Serializer subclass.

Here's the gotcha I'd warn every Django developer about: TypeScript types don't exist at runtime. @Body() dto: CreateOrderDto with no schema and no pipe accepts whatever JSON the client sent, and the type annotation checks nothing. Python developers expect the opposite, because a serializer always runs.

Output needs no serializer. A handler returns a plain object, and its JSON is the response. To leave a field out, such as a password hash, don't select it, or return an object without it.

Users, sign-in and permissions

django.contrib.auth gives you a User model, password hashing, sessions and permission tables. @nestjs/authentication gives you the sign-in parts, and leaves the users to you:

  • Users are your table. The package never reads it. It asks your code for a user by id, and a user is whatever type your app defines. No AbstractUser, no AUTH_USER_MODEL.
  • Passwords are hashed by PasswordHasher, with scrypt at OWASP's parameters, the job of make_password() and check_password(). An unknown email takes as long to check as a wrong password, and needsRehash() tells you when to upgrade an old hash on sign-in, as Django does.
  • Sessions are server-side, in an HttpOnly, Secure cookie, like the database session backend, and SignInService.signIn() is login(). The one thing Django does that the package doesn't: it creates no tables. Sessions go in your database through a store you write against its interfaces, with the package's own tests to check it.
  • Every route is closed by default. @Public() opens one, which turns login_required inside out. @CurrentUser() is request.user.
  • What you'd install django-allauth for is in the box: email verification, password reset links, TOTP two-factor authentication, magic links, sign-in with Google and other OpenID Connect providers, access and refresh tokens, and API keys that users create and revoke.

Permissions are code, not rows. Django stores add_order, change_order and friends per model, assigns them to groups, and checks them with has_perm(). @nestjs/authorization replaces those, and DRF's permission classes, with policies. Here's a DRF object permission:

# orders/permissions.py class IsOrderOwnerOrStaff(permissions.BasePermission): def has_object_permission(self, request, view, obj): user = request.user return user.is_staff or obj.customer_id == user.customer.id 

The same check as a policy, with a staff-only refund next to it:

// orders/order.policy.ts import { Policy } from '@nestjs/authorization'; import type { User } from '../users/user.js'; import type { Order } from './order.js'; @Policy() export class OrderPolicy { view(user: User | null, order: Order) { if (!user) { return false; } return user.roles.includes('staff') || order.customerId === user.id; } refund(user: User | null) { return !!user?.roles.includes('staff'); } } 

A check that needs only the user goes on the route, as @Can(OrderPolicy, 'refund'). A check that needs the record, the has_object_permission() case, goes in the service once the record is loaded:

async findOne(user: User, id: string) { const order = await this.ordersRepository.findById(id); if (!order) { throw new NotFoundException(); } await this.authorizat...
Source:https://dev.to/nestjs/is-there-a-django-for-nodejs-a-nestjs-guide-for-django-developers-pba