JavaScript

Building REST APIs with Node.js: Where TypeScript Shines

Building a REST API shouldn't require fighting your programming language.

Most web APIs do relatively ordinary things. They receive JSON, validate input, query a database, apply business rules, and return a response.

Yet the amount of code required to accomplish these tasks varies considerably between languages and frameworks.

Node.js and TypeScript offer an interesting combination: a dynamic runtime, static type checking, native JSON support, mature asynchronous programming, and an ecosystem that extends naturally into frontend development.

That doesn't make JavaScript the best language for every backend. Go, Python, Java, and Kotlin all have compelling advantages.

But when the job is building a JSON API from scratch, Node.js deserves a closer look.

Let's explore why.


JSON Feels Native in JavaScript

One of the nicest things about building APIs in JavaScript is how little translation happens between your application data and the HTTP response.

Consider a simple user profile:

const user = {
  id: 42,
  name: 'Alex',
  email: 'alex@example.com',
  roles: ['editor', 'admin']
};

const json = JSON.stringify(user);

That's it. No serialization annotations, additional dependencies, or mapping configuration.

With a framework like Fastify, you don't even need to call JSON.stringify manually:

app.get('/api/user', async () => {
  return {
    id: 42,
    name: 'Alex',
    roles: ['editor']
  };
});

The framework handles the HTTP response.

Of course, JavaScript serialization has limitations. Map, Set, BigInt, circular references, and undefined values require special attention.

There's also a security consideration. Returning an entire database record can accidentally expose internal fields.

A better approach is to explicitly construct your response:

function toPublicUser(user: User) {
  return {
    id: user.id,
    name: user.name
  };
}

Native JSON support doesn't eliminate the need for thoughtful API design. It simply removes a layer of unnecessary ceremony.


Database Queries Without Unnecessary Mapping

Many Node.js database drivers return query results as ordinary JavaScript objects. For JSON APIs, that's particularly convenient.

Here's an example using PostgreSQL and Fastify:

import Fastify from 'fastify';
import pg from 'pg';

const app = Fastify();

const db = new pg.Pool({
  connectionString: process.env.DATABASE_URL
});

type User = {
  id: number;
  name: string;
  email: string;
};

app.get('/api/users', async () => {
  const { rows } = await db.query<User>(
    'SELECT id, name, email FROM users'
  );

  return rows;
});

await app.listen({ port: 3000 });

The database driver returns an array of objects. Fastify serializes it into JSON.

There is no requirement to introduce an ORM just to expose a collection of records through an HTTP endpoint.

For more complex applications, tools such as Drizzle, Kysely, Prisma, and Knex offer different levels of abstraction.

The important thing is having a choice.

Start with SQL when SQL is enough. Introduce additional abstractions when they solve an actual problem.

One caveat: the TypeScript generic passed to db.query describes the expected result. It does not independently verify the database schema or validate returned values at runtime.


Async/Await Makes Backend Code Easier to Read

A typical API spends much of its time waiting.

Waiting for PostgreSQL. Waiting for Redis. Waiting for another service to respond.

JavaScript's asynchronous execution model fits this kind of workload naturally.

Imagine an endpoint that returns a customer together with their recent orders.

async function getCustomer(id: number) {
  const customer = await findCustomer(id);

  if (!customer) {
    throw new NotFoundError('Customer not found');
  }

  const orders = await findOrders(id);

  return {
    ...customer,
    orders
  };
}

The code reads in the same order as the business operation.

When two operations don't depend on each other, they can run concurrently:

async function getDashboard(userId: number) {
  const [profile, orders, notifications] =
    await Promise.all([
      getProfile(userId),
      getOrders(userId),
      getNotifications(userId)
    ]);

  return {
    profile,
    orders,
    notifications
  };
}

Instead of waiting for each request to finish before starting the next one, all three operations can make progress concurrently.

This is useful when building dashboards, aggregating external APIs, or retrieving independent resources.

It isn't free performance, though. Unrestricted concurrency can overwhelm database connection pools and external services.

Use concurrency deliberately.


Centralized Error Handling

Error handling can quickly dominate backend code.

A useful pattern in Node.js is to keep business logic focused on successful execution and handle HTTP errors at the framework boundary.

First, define an application error:

class HttpError extends Error {
  constructor(
    public statusCode: number,
    message: string
  ) {
    super(message);
  }
}

Then configure a centralized Fastify error handler:

app.setErrorHandler((error, request, reply) => {
  if (error instanceof HttpError) {
    return reply.code(error.statusCode).send({
      error: error.message
    });
  }

  request.log.error(error);

  return reply.code(500).send({
    error: 'Internal server error'
  });
});

Individual route handlers remain relatively small:

app.get('/api/products/:id', async (request) => {
  const { id } = request.params as {
    id: string;
  };

  const product = await findProduct(id);

  if (!product) {
    throw new HttpError(404, 'Product not found');
  }

  return product;
});

Unexpected errors reach the centralized handler, while application errors produce appropriate HTTP responses.

There is no need to wrap every asynchronous operation in an identical try/catch block.

Local error handling still matters when an operation requires recovery, retries, resource cleanup, or additional context.

Centralized handling simply prevents repetitive HTTP response logic from leaking into every service.


TypeScript Is More Than Autocomplete

TypeScript becomes particularly valuable as a backend grows.

Consider an order service:

type OrderStatus =
  | 'pending'
  | 'paid'
  | 'shipped'
  | 'cancelled';

interface Order {
  id: string;
  customerId: string;
  total: number;
  status: OrderStatus;
}

async function findOrder(
  id: string
): Promise<Order | null> {
  return repository.findById(id);
}

The function signature communicates several things immediately.

The operation is asynchronous. It returns an Order when successful. It may also return null.

With strict type checking enabled, consumers cannot safely treat the result as an existing order without first checking it.

const order = await findOrder('order-42');

if (!order) {
  throw new HttpError(404, 'Order not found');
}

console.log(order.total);

Discriminated unions are equally useful for modeling business operations.

type PaymentResult =
  | { success: true; transactionId: string }
  | { success: false; reason: string };

function handlePayment(result: PaymentResult) {
  if (result.success) {
    return result.transactionId;
  }

  throw new Error(result.reason);
}

The compiler understands which properties are available in each branch.

These features also make AI-assisted development easier to review. Generated code has explicit contracts to follow, and many inconsistencies can be caught before execution.

TypeScript doesn't guarantee correctness. But it makes entire categories of mistakes easier to detect.


Static Types Are Not Runtime Validation

Here's where TypeScript developers sometimes get into trouble.

An interface describes what your application expects. It cannot guarantee that an incoming HTTP request actually contains that data.

This code provides no runtime protection:

interface CreateUser {
  name: string;
  email: string;
  age: number;
}

const user = request.body as CreateUser;

The assertion tells TypeScript to trust the value. It does not inspect the request body.

For external input, use runtime validation.

Here's an example with Zod:

import { z } from 'zod';

const CreateUserSchema = z.object({
  name: z.string().trim().min(2),
  email: z.string().email(),
  age: z.number().int().min(18)
});

type CreateUser = z.infer<
  typeof CreateUserSchema
>;

app.post('/api/users', async (request, reply) => {
  const result = CreateUserSchema.safeParse(
    request.body
  );

  if (!result.success) {
    return reply.code(400).send({
      error: 'Invalid request',
      details: result.error.issues
    });
  }

  const user = await createUser(result.data);

  return reply.code(201).send(user);
});

Now the application validates incoming data before passing it to business logic.

The TypeScript type is inferred directly from the validation schema, reducing duplication.

Fastify's JSON Schema support, Valibot, and TypeBox are also worth exploring.

A useful rule: validate data when it crosses a trust boundary, then use static types throughout the internal application.


Sharing Types Between Frontend and Backend

One of the strongest arguments for TypeScript on the server has little to do with server performance.

It's the frontend.

When both sides of an application use TypeScript, they can share API contracts directly.

A monorepo might look like this:

project/
  apps/
    web/
    api/
  packages/
    contracts/
      src/
        user.ts
        order.ts

Inside the shared contracts package:

import { z } from 'zod';

export const UserSchema = z.object({
  id: z.string(),
  name: z.string(),
  email: z.string().email()
});

export type User = z.infer<typeof UserSchema>;

The backend uses the contract to construct or validate its response.

The frontend uses the same contract when consuming the API:

import {
  UserSchema,
  type User
} from '@app/contracts';

export async function getUser(
  id: string
): Promise<User> {
  const response = await fetch(`/api/users/${id}`);

  if (!response.ok) {
    throw new Error('Failed to load user');
  }

  return UserSchema.parse(await response.json());
}

If the API contract changes, both applications can be checked against the updated definition.

This reduces a familiar source of frontend bugs: assumptions about what the server returns.

Other languages can achieve similar results using OpenAPI, generated clients, or Protocol Buffers. TypeScript simply makes direct sharing particularly convenient.

The benefits extend beyond types. Both applications can use the same package manager, formatter, linter, testing tools, and workspace configuration.


Choosing a Node.js Framework

The Node.js ecosystem doesn't force every backend into the same architectural model.

You can choose a framework based on the size of your application and the conventions your team needs.

Express

https://expressjs.com/

A familiar, flexible framework with a large middleware ecosystem. Express 5 also supports automatic forwarding of rejected promises from asynchronous route handlers.

Hono

https://hono.dev/

A lightweight framework built around web standards. Particularly interesting for APIs that need to run across different JavaScript runtimes and edge environments.

Fastify

https://fastify.dev/

A strong choice for dedicated REST APIs. It offers schema-based validation, serialization, structured logging, hooks, and an extensible plugin architecture.

NestJS

https://nestjs.com/

A more opinionated framework with modules, dependency injection, controllers, guards, and interceptors. Useful when a large team benefits from consistent architectural conventions.

Koa

https://koajs.com/

A minimal framework centered around asynchronous middleware. It provides a small foundation while leaving many architectural decisions to the developer.

Full-stack frameworks such as Next.js, Nuxt, SvelteKit, and TanStack Start are another option when the frontend and backend belong to the same application.

There is no universal winner.

A small internal API may need nothing more than Hono. A dedicated backend might benefit from Fastify. A large enterprise application could justify the additional structure provided by NestJS.


Where Node.js Performance Comes From

JavaScript is often described as single-threaded. That's an incomplete description of Node.js.

JavaScript callbacks normally execute on the main event loop, but the runtime can coordinate asynchronous network operations, operating system facilities, and a worker pool.

For an I/O-heavy API, this allows the server to handle other requests while waiting for external operations to complete.

A database query doesn't need to occupy the JavaScript thread until PostgreSQL responds.

CPU-intensive JavaScript is different.

Consider this deliberately inefficient endpoint:

app.get('/api/calculate', async () => {
  let result = 0;

  for (let i = 0; i < 1_000_000_000; i++) {
    result += Math.sqrt(i);
  }

  return { result };
});

Adding async to the function does not make the calculation non-blocking.

While the loop executes, other requests may experience significant delays.

For computational workloads, consider worker threads, background jobs, separate processes, or a dedicated service written in a language better suited to the task.

Node.js is particularly effective when the application spends more time coordinating operations than performing expensive calculations.

Performance comparisons should therefore use realistic workloads, including database access, validation, serialization, authentication, memory consumption, and response latency.

A benchmark that returns a static JSON object tells you very little about the performance of a complete production application.


Node.js vs. Python

Python is probably the closest alternative to JavaScript when development speed is the priority.

FastAPI, in particular, provides an excellent developer experience for building typed HTTP APIs.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    id: int
    name: str

@app.get("/users/{user_id}")
async def get_user(user_id: int) -> User:
    return User(id=user_id, name="Alex")

FastAPI combines routing, validation, serialization, and automatic API documentation with remarkably little code.

Python becomes especially attractive when the backend is closely connected to machine learning, data processing, scientific computing, or AI services.

Node.js has an advantage when the same team also maintains a TypeScript frontend and wants to share tooling and application contracts.

Python's asynchronous ecosystem is mature, but developers need to understand how synchronous functions interact with the event loop and thread pools.

Choose Python when its ecosystem is central to the application. Choose TypeScript when web development and frontend integration dominate the workload.


Node.js vs. Go

Go approaches backend development from a different direction.

It emphasizes explicit behavior, straightforward concurrency, fast compilation, and simple deployment.

A small HTTP server requires only the standard library:

package main

import (
    "encoding/json"
    "log"
    "net/http"
)

type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

func main() {
    http.HandleFunc("/api/user",
        func(w http.ResponseWriter, r *http.Request) {
            w.Header().Set(
                "Content-Type", "application/json",
            )

            err := json.NewEncoder(w).Encode(
                User{ID: 42, Name: "Alex"},
            )

            if err != nil {
                log.Println(err)
            }
        },
    )

    log.Fatal(http.ListenAndServe(":3000", nil))
}

Go is particularly attractive for infrastructure services, networking tools, distributed systems, and applications that benefit from predictable resource usage.

Its explicit error handling is a deliberate design choice. Some developers appreciate seeing every potential failure directly in the code. Others prefer the exception-based approach used by JavaScript.

Go's goroutines also make concurrent programming accessible without relying on JavaScript's execution model.

Node.js generally offers more direct integration with browser applications. Go offers a compelling operational model for independent backend services.

Both are excellent choices for HTTP APIs.


Node.js vs. Java

Java remains one of the strongest platforms for large backend systems.

Its ecosystem includes mature solutions for persistence, messaging, transactions, security, monitoring, and distributed application architecture.

Modern Java is also considerably less verbose than its reputation suggests.

With Spring Boot and records, a simple controller can look like this:

record User(long id, String name) {}

@RestController
class UserController {

    @GetMapping("/api/user")
    public User getUser() {
        return new User(42, "Alex");
    }
}

Spring Boot handles routing and JSON serialization through its framework integrations.

The additional architecture becomes valuable when applications require sophisticated authorization, transaction management, dependency injection, or integration with established enterprise infrastructure.

Node.js offers a different starting point. You can begin with a minimal HTTP framework and introduce architecture as requirements become clearer.

Java is not inherently unsuitable for small APIs, and Node.js is not inherently unsuitable for enterprise applications.

The real difference is often the ecosystem, team experience, and preferred architectural conventions.


Node.js vs. Kotlin

Kotlin is an interesting option for developers who appreciate modern language features but want access to the JVM ecosystem.

It offers concise syntax, null safety, data classes, extension functions, and coroutine-based asynchronous programming.

A Spring controller written in Kotlin can be pleasantly small:

data class User(
    val id: Long,
    val name: String
)

@RestController
class UserController {

    @GetMapping("/api/user")
    fun getUser(): User {
        return User(42, "Alex")
    }
}

Kotlin developers can also choose Ktor, a lighter framework that provides a more flexible approach to building HTTP services.

For teams already using Java libraries and JVM infrastructure, Kotlin can provide many of the productivity benefits associated with modern languages without requiring a completely different platform.

TypeScript still has the advantage of direct language compatibility with frontend applications.

Kotlin is particularly compelling when JVM interoperability matters more than sharing application code with the browser.


When Node.js Is Not the Best Choice

Node.js has limitations, and ignoring them leads to poor architectural decisions.

Consider alternatives when your application involves:

  • Heavy numerical computation or image processing.
  • CPU-intensive operations with strict latency requirements.
  • Infrastructure services with tight memory budgets.
  • Large-scale data processing or scientific workloads.
  • Existing enterprise systems built around another ecosystem.
  • Teams with significantly stronger expertise in Go, Python, Java, or Kotlin.

Node.js can handle binary protocols, gRPC, background processing, and computational tasks. The question is whether it provides the most convenient and efficient solution for your particular workload.

Sometimes the best architecture combines several languages.

A TypeScript API can coordinate requests, a Python service can run machine learning models, and a Go service can handle infrastructure-intensive operations.

There's no requirement for every component of a distributed system to use the same programming language.

Choose the platform that fits the problem rather than forcing the problem to fit the platform.


A Small API You Can Actually Build

Let's put the ideas together in a small TypeScript REST API.

We'll use Fastify, Zod, and an in-memory repository. The example supports creating and retrieving tasks, validates incoming data, and returns appropriate HTTP status codes.

Start by installing the dependencies:

npm init -y
npm install fastify zod
npm install -D typescript tsx @types/node

Create a tsconfig.json file:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  }
}

Create server.ts:

import Fastify from 'fastify';
import { randomUUID } from 'node:crypto';
import { z } from 'zod';

const app = Fastify({ logger: true });

const TaskSchema = z.object({
  title: z.string().trim().min(1).max(200),
  completed: z.boolean().default(false)
});

type Task = z.infer<typeof TaskSchema> & {
  id: string;
};

const tasks = new Map<string, Task>();

app.get('/api/tasks', async () => {
  return [...tasks.values()];
});

app.get<{ Params: { id: string } }>(
  '/api/tasks/:id',
  async (request, reply) => {
    const task = tasks.get(request.params.id);

    if (!task) {
      return reply.code(404).send({
        error: 'Task not found'
      });
    }

    return task;
  }
);

app.post('/api/tasks', async (request, reply) => {
  const result = TaskSchema.safeParse(
    request.body
  );

  if (!result.success) {
    return reply.code(400).send({
      error: 'Invalid task',
      details: result.error.issues
    });
  }

  const task: Task = {
    id: randomUUID(),
    ...result.data
  };

  tasks.set(task.id, task);

  return reply.code(201).send(task);
});

async function start() {
  await app.listen({ port: 3000 });
}

start().catch((error) => {
  app.log.error(error);
  process.exit(1);
});

Run the TypeScript compiler to check the application:

npx tsc --noEmit

Start the development server:

npx tsx watch server.ts

Open http://localhost:3000/api/tasks to retrieve the task collection.

To create a task, send a POST request to the same endpoint with the following JSON body:

{
  "title": "Learn Fastify",
  "completed": false
}

The server returns a newly created task with a generated identifier.

This example deliberately avoids databases, authentication, dependency injection, and additional architectural layers.

The repository is stored in memory, so data disappears when the process restarts.

As the application grows, you can replace the Map with PostgreSQL, move business logic into services, introduce authentication, and add integration tests.

You don't have to solve every architectural problem on day one.


Final Thoughts

Node.js and TypeScript aren't the answer to every backend problem.

What makes them appealing is the combination of a relatively small amount of application code, mature asynchronous programming, flexible architecture, and a natural connection to frontend development.

You can build a working API with a handful of dependencies, introduce runtime validation, share contracts with the frontend, and gradually improve the architecture as the application grows.

Go offers excellent deployment characteristics. Python brings an exceptional ecosystem for AI and data processing. Java and Kotlin provide mature foundations for complex backend systems.

None of those advantages disappear just because JavaScript is convenient.

But for a new JSON REST API, especially one built alongside a TypeScript frontend, Node.js remains a remarkably productive choice.

The best backend is not necessarily the one with the fastest synthetic benchmark or the most sophisticated architecture.

It's the one your team can build, understand, operate, and improve without unnecessary complexity.