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 theapi/fromurls.py. - Route parameters arrive as strings.
ParseUUIDPipeorParseIntPipeconverts and checks one, like a path converter. - A
POSTanswers201by default and everything else200.@HttpCode()changes it. - A handler returns the body, and Nest serializes it as JSON.
get_object_or_404()becomesthrow new NotFoundException()in the service. - There's no
IsAuthenticatedabove, 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, noAUTH_USER_MODEL. -
Passwords are hashed by
PasswordHasher, with scrypt at OWASP's parameters, the job ofmake_password()andcheck_password(). An unknown email takes as long to check as a wrong password, andneedsRehash()tells you when to upgrade an old hash on sign-in, as Django does. -
Sessions are server-side, in an
HttpOnly,Securecookie, like the database session backend, andSignInService.signIn()islogin(). 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 turnslogin_requiredinside out.@CurrentUser()isrequest.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.authorizationService.authorize(OrderPolicy, 'view', user, order);
return order;
}
authorize() throws when the policy says no, which answers 403, or 401 to a guest. And like authentication, the authorization guard denies by default: a route with no check declared is closed. Roles and groups are fields on your user, stored however you like. For organizations, members and roles in a B2B app, the docs have a multi-tenant SaaS tutorial.
Settings become configuration
settings.py is Python that runs at startup and usually reads os.environ. @nestjs/config reads .env files and environment variables, and validates them before the app starts, so a missing DATABASE_URL is a startup error, not a 500 on the first request:
// app.module.ts
import { ConfigModule } from '@nestjs/config';
import { z } from 'zod';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
validationSchema: z.object({
DATABASE_URL: z.url(),
SMTP_URL: z.url(),
DEBUG: z.stringbool().default(false),
}),
}),
],
})
export class AppModule {}
There's no global settings object to import. A provider that needs a value injects ConfigService and calls get(), or getOrThrow() for a required one.
send_mail() becomes Mailer from @nestjs/mail. Here's the usual Django version, rendering a template and sending it:
# orders/emails.py
def send_order_confirmation(order):
html = render_to_string("emails/order_confirmation.html", {"order": order})
send_mail(
f"Your order #{order.number}",
strip_tags(html),
None,
[order.customer.email],
html_message=html,
)
In Nest, a mail is a class that returns the subject, the template's name and the values the template reads:
// notifications/order-confirmation.mail.ts
import { Injectable } from '@nestjs/common';
import type { Mailable } from '@nestjs/mail';
import type { Order } from '../orders/order.js';
@Injectable()
export class OrderConfirmationMail implements Mailable<{ order: Order }> {
render({ order }: { order: Order }) {
return {
subject: `Your order #${order.number}`,
template: 'order-confirmation',
context: { order },
};
}
}
A service sends it, and the type of data comes from the mail class:
await this.mailer.send(OrderConfirmationMail, {
to: { name: customer.name, address: customer.email },
data: { order },
});
Templates escape every value, as Django's do. In development, FileMailTransport writes each mail to a file instead of sending it, like the file email backend; in production, SMTP or Resend sends it; and in tests, InMemoryMailTransport keeps what was sent, like mail.outbox.
Files and translations
django-storages becomes @nestjs/storage: named disks (a local folder, S3, or R2 and other S3-compatible stores) behind one API. default_storage.save() is put(), .url() is url(), and a private file gets a signed link:
// invoices/invoices.service.ts
import { Injectable } from '@nestjs/common';
import { InjectDisk, StorageDisk } from '@nestjs/storage';
@Injectable()
export class InvoicesService {
constructor(@InjectDisk('private') private readonly files: StorageDisk) {}
async store(orderId: string, pdf: Buffer) {
const key = `invoices/${orderId}.pdf`;
await this.files.put(key, pdf, { contentType: 'application/pdf' });
return this.files.signedUrl(key, { expiresIn: '15m' });
}
}
Uploads stream straight onto a disk with uploadToDisk(), rather than through memory or a temp file.
gettext and .po files become @nestjs/i18n, with a JSON catalog per language. Keys are typed, so _("Order not found") turns into a key that fails to compile if you misspell it:
throw new NotFoundException(this.i18n.t('orders.notFound', { args: { id } }));
Plurals follow each language's rules, like ngettext(), and the locale comes from Accept-Language, a query parameter, a cookie or the user's saved language, the job LocaleMiddleware does. Validation messages and exceptions get translated too.
Celery, beat and signals
A Celery task becomes a job on a BullMQ queue, which runs on Redis, the way Celery usually does. Here's a task and the call that queues it:
# orders/tasks.py
@shared_task
def generate_invoice(order_id):
...
generate_invoice.delay(order.id)
In Nest, a processor class takes the queue's jobs:
// invoices/invoice.processor.ts
import { Processor, WorkerHost } from '@nestjs/bullmq';
import type { Job } from 'bullmq';
@Processor('invoices')
export class InvoiceProcessor extends WorkerHost {
async process(job: Job<{ orderId: string }>) {
// ...
}
}
A service adds a job to the queue it injects, as delay() does:
// constructor(@InjectQueue('invoices') private readonly invoices: Queue) {}
await this.invoices.add('generate', { orderId: order.id });
The processor is a provider like any other, so it injects your services. No separate Celery app with its own settings: workers run in the app's process, or in another process that starts the same modules.
Celery beat becomes @Cron() from @nestjs/schedule, on any provider's method. A scheduled method runs on every instance of the app, so on more than one instance, add @OnOneInstance() from @nestjs/locks.
Signals become events, emit() and @OnEvent() from @nestjs/event-emitter. There's no post_save, because there's no model layer to send it: emit the event from the service that saved the row, which I'd argue is where you wanted it anyway.
And transaction.on_commit(), for "send the email only once the order is saved", has a stronger version: @nestjs/outbox writes the message in the same transaction as the order and delivers it after the commit, retrying until it's sent, even if the process dies in between.
Caching, rate limiting, CSRF and templates
-
Caching:
@nestjs/cache-managergives youget(),set()anddel()likedjango.core.cache, andCacheInterceptorcaches whole responses likecache_page. -
Rate limiting:
@nestjs/throttlerlimits requests per client and window, like DRF's throttle classes, with@Throttle()and@SkipThrottle()per route. -
CSRF:
app.enableCsrfProtection()refuses state-changing requests from other origins, using theSec-Fetch-SiteandOriginheaders browsers send, so there's no token to put in forms. -
Templates: most Nest apps are APIs with a separate frontend. If you render HTML on the server, set a view engine such as Handlebars and return a template's context from a handler marked
@Render('products/detail').
Management commands and the shell
A management command becomes a script that starts the app's modules without the HTTP server:
// scripts/close-stale-carts.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from '../app.module.js';
import { CartsService } from '../carts/carts.service.js';
const app = await NestFactory.createApplicationContext(AppModule);
await app.get(CartsService).closeStale();
await app.close();
For commands with arguments, options and help text, nest-commander gives you what BaseCommand does. And manage.py shell has a counterpart in Nest's REPL, where every provider is at hand: await get(OrdersService).findOne(...).
The admin
Nest has no admin. It's the one Django battery with no first-party counterpart, and for a team that runs its back office in the Django admin, it's the biggest thing you give up. I'd rather you hear that from me now than find out in week three.
What teams do instead:
- A third-party admin panel. AdminJS has a Nest integration and generates CRUD screens from your models.
- A database GUI for the people who only browse and fix rows.
- Internal pages in your own frontend, on the same API and the same policies as the rest of the app. That's more work up front, and it means one permission model instead of two.
Testing
TestCase and APIClient become a testing module and Supertest. This test creates only the controller, with a fake service in place of the real one:
// orders/orders.controller.spec.ts
import { Test } from '@nestjs/testing';
import type { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { vi } from 'vitest';
import { OrdersController } from './orders.controller.js';
import { OrdersService } from './orders.service.js';
describe('OrdersController', () => {
let app: INestApplication;
const ordersService = { findForCustomer: vi.fn() };
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
controllers: [OrdersController],
providers: [{ provide: OrdersService, useValue: ordersService }],
}).compile();
app = moduleRef.createNestApplication();
await app.init();
});
afterAll(() => app.close());
it('lists orders', async () => {
ordersService.findForCustomer.mockResolvedValue([]);
await request(app.getHttpServer()).get('/orders').expect(200, []);
});
});
For a test of the whole app, import AppModule and swap providers with overrideProvider(). One thing Django spoils you with: its test runner creates a test database, runs migrations and wraps each test in a transaction. Nest doesn't. Point DATABASE_URL at a test database, run the migrations before the suite, and clean the tables between tests (Testcontainers makes the first part painless).
OpenAPI and health checks
drf-spectacular becomes @nestjs/swagger, which builds the OpenAPI document from your controllers and schemas and serves Swagger UI, the closest thing to DRF's browsable API. Health endpoints for your load balancer come from @nestjs/terminus, with checks for the database, other services, disk and memory.
Shipping it
A Django app ships as Python code behind Gunicorn or uWSGI, often with a separate Celery worker. A Nest app ships as compiled JavaScript plus its node_modules, almost always in a container. A production Dockerfile, built in one stage and run in another:
FROM node:24-slim AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev
FROM node:24-slim
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build /app/package.json ./
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
USER node
CMD ["node", "--enable-source-maps", "dist/main.js"]
Three things to check that Gunicorn handled for you:
-
Graceful shutdown. Call
app.enableShutdownHooks()inmain.ts, soonApplicationShutdown()runs onSIGTERMand connections close cleanly. -
The process gets the signal. Use the exec form,
CMD ["node", ...], notnpm start, which doesn't reliably forward signals. - More cores means more processes. Gunicorn starts several workers; one Node process uses one core for your code. Run several containers, or several processes per container, behind the load balancer.
And run migrations as a release step (drizzle-kit migrate), not on startup, so two instances starting at once don't race, the same advice you'd follow with manage.py migrate.
Moving over without a rewrite
You don't have to port a Django codebase to start using Nest:
-
Start with a new service, not a port. The next thing you need gets written in Nest, behind the same proxy or ingress, against the same Postgres if that's simpler. Nest doesn't care that Django created the tables: point Drizzle at them, and
drizzle-kit pullwrites a schema from the existing database. -
Share the contract, not the code. If your DRF API publishes an OpenAPI document, generate a TypeScript client from it for the Nest service, and the other way round with
@nestjs/swagger. - Move endpoints only when you'd rewrite them anyway, one path at a time behind the proxy.
What's actually different
The syntax takes a week. These take longer.
One process serves many requests at once. A Gunicorn worker handles one request at a time. Node runs your code on one thread with an event loop: while a request waits for Postgres, the others run. That's why one Node process handles thousands of concurrent connections, the promise Django's async views make, but everywhere and by default. The flip side: CPU-heavy work in a handler, such as resizing an image or a long loop over a big list, stalls every other request in that process. Move it to a queue or a worker thread. If your service is mostly number crunching or data science, Python is the better home, and I'd say so to anyone.
await everything. Database drivers and HTTP clients are asynchronous. A forgotten await doesn't block, it lets the code carry on before the query has finished, and the bug shows up somewhere else. The no-floating-promises lint rule catches most of them, and nest new turns it on, so keep npm run lint in CI.
No thread-local request. There's no global request to reach for from a helper. Pass the user into the service, or read per-request state from AsyncLocalStorage, which follows a request through every await.
Everything is wired explicitly. Django finds your models, admin classes, management commands and templates by convention. Nest configures nothing because a package is installed, and runs nothing because a file exists.
Batteries are separate packages. Django is one package, released as a whole. Nest's core and each first-party package are installed separately, so a project carries only what it uses. Upgrade them together.
Types are a compile-time check. I said it above and I'll say it again, because it's the one that bites Python developers: a type annotation describes what you expect and checks nothing at runtime. A request body, a raw query's rows, a queue message: only a schema checks them.
Numbers are doubles. There's no Decimal. Keep money in integer cents, or use a decimal library and your database's numeric type, which most drivers return as a string anyway.
ES modules. A new project imports local files with a .js extension, even from .ts files, because that's the name of the compiled file. It looks wrong for about a day.
When I'd stay on Django
To be fair to Django: if the admin is how your company runs, if your team is all Python and happy, or if the backend lives next to data science and machine learning code in Python, stay. Django's maturity, its admin and its ecosystem of reusable apps are real advantages, and a rewrite to get TypeScript is rarely worth it on its own.
Nest is a good fit when the new thing is a new service, when the people building it also write the TypeScript frontend, or when you want one language from the browser to the database, with batteries close to the ones you're used to.
Getting started
npx @nestjs/cli new orders-api
cd orders-api
npm run start:dev
Then nest g resource orders, and you have a module, controller, service, DTOs and tests to hold up against the Django app in your head. The Coming from Django page in the docs keeps this mapping as a reference, with a link from each row to its full chapter.
If something here doesn't match how you'd do it in Django, tell me. It's written for you, and it's easy to fix.
Coming from Java or .NET instead? Here's the same tour for Spring Boot and for ASP.NET Core.
Top comments (0)