TypeScript with Node.js
TypeScript with Node.js is the standard way to build typed backends. Node.js runs the JavaScript, and TypeScript checks your code before it runs. You get autocomplete for Node APIs, safer request handlers, and fewer runtime crashes. In real projects, this combination powers APIs, background jobs, and command-line tools.
This tutorial shows you how to set up a Node project with TypeScript, write a Node-appropriate tsconfig.json, structure src and dist folders, add npm scripts for dev, build, and start, run with tsx or ts-node, and build a tiny Express server with typed Request and Response. You will also see why the compiled dist folder is what runs in production.
How Do You Set Up a Node Project with TypeScript?
Start with npm init to create a package.json, then install TypeScript and @types/node. The @types/node package provides type definitions for Node.js built-in modules like fs, path, and process. Without it, the compiler does not know about Node's APIs.
Here are the setup commands:
mkdir my-api
cd my-api
npm init -y
npm install -D typescript @types/node tsx
The -D flag installs these as development dependencies. tsx is a fast runner that executes TypeScript directly, which is handy during development. You should also install Express and its types for the server example later:
npm install express
npm install -D @types/express
After these commands, you have a package.json with the right tools. The next step is the tsconfig.json.
What Does a Node-Appropriate tsconfig.json Look Like?
A tsconfig.json tells the compiler how to build your project. For Node.js, you want a modern target, a Node-compatible module setting, separate outDir and rootDir, and strict mode on. This config works with Node.js 18 and later.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
How it works: target sets the JavaScript version that Node.js will run. module and moduleResolution set to NodeNext make TypeScript follow Node.js module rules, including the .js extension in relative imports. outDir is where compiled files go, and rootDir is where source files live. strict turns on all strict checks. esModuleInterop helps import CommonJS packages like Express. skipLibCheck speeds up builds by skipping type checks in library files. sourceMap helps with debugging.
How Should You Structure Your Project?
A clear structure keeps source and build output separate. Put all TypeScript files in src and let the compiler write JavaScript to dist. The dist folder is generated, so you should add it to .gitignore and never edit it by hand.
my-api/
src/
index.ts
dist/
index.js
package.json
tsconfig.json
How it works: rootDir is ./src, so every .ts file lives there. outDir is ./dist, so compiled output mirrors the source tree. When you run the build, src/index.ts becomes dist/index.js. Node.js runs the file in dist, not the one in src. This separation keeps your repository clean and your production artifact predictable.
What npm Scripts Should You Add?
npm scripts are shortcuts defined in package.json. Add three: dev for local development with auto-restart, build for compiling, and start for running the compiled output. This is the standard workflow.
{
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc",
"start": "node dist/index.js"
}
}
How it works: dev uses tsx watch to run the TypeScript file and restart when it changes. build runs tsc, which reads tsconfig.json and compiles everything in src to dist. start runs the compiled JavaScript with Node. In production, you run npm run build once, then npm start. You never run tsx in production because it does not type-check and adds overhead.
How Do You Run TypeScript During Development?
During development, you want fast feedback. Use tsx or ts-node to run .ts files directly. Both strip types and execute the code in Node. tsx is generally faster and works with modern module syntax out of the box. Add nodemon or use the built-in watch mode for auto-restart.
npx tsx src/index.ts
If you prefer ts-node, install it and run:
npm install -D ts-node
npx ts-node src/index.ts
How it works: tsx and ts-node read your .ts file, remove the type annotations, and pass the JavaScript to Node. They do not produce a dist folder. That is fine for development. For type checking, run npx tsc --noEmit separately, because these runners skip full type checks for speed. The tsx watch command in the dev script handles auto-restart when files change.
How Do You Build a Typed Express Server?
Express is a popular Node.js web framework. With TypeScript, you type Request and Response using @types/express. This gives you correct properties like req.params, req.body, and res.json. Here is a small typed server with a Hello route.
import express from "express";
import type { Request, Response } from "express";
const app = express();
const port = 3000;
app.get("/", (_req: Request, res: Response) => {
res.json({ message: "Hello from TypeScript!" });
});
app.get("/users/:id", (req: Request, res: Response) => {
const { id } = req.params;
res.json({ id, name: "Riya" });
});
app.listen(port, () => {
console.log(`Server on http://localhost:${port}`);
});
// Output when visiting /: { "message": "Hello from TypeScript!" }
// Output when visiting /users/1: { "id": "1", "name": "Riya" }
How it works: express() creates the app. app.get("/") registers a handler for GET requests to the root path. The handler receives a Request and a Response, both typed by @types/express. res.json sends a JSON response. The second route reads req.params.id, which is a string. app.listen starts the server on port 3000. If you typed res.send with a non-string object, the compiler would warn you unless you used res.json. The types come from @types/express, which is why installing it is essential.
Why Does the Compiled dist Folder Run in Production?
Node.js cannot run TypeScript directly. It runs JavaScript. In production, you want the compiled output, not the source. The dist folder contains plain JavaScript that Node can execute without any TypeScript tooling. This is also what you copy into a Docker image or a server.
npm run build
npm start
How it works: npm run build runs tsc, which reads tsconfig.json and writes JavaScript to dist. npm start runs node dist/index.js. The production server does not need typescript, tsx, or ts-node installed. You can install only production dependencies with npm ci --omit=dev in your deployment. This keeps the image small and the startup fast. The dist folder is the artifact that runs, so never edit it by hand and always rebuild after changes.
Development vs Production: What Is the Difference?
| Feature | Development | Production |
|---|---|---|
| Runner | tsx watch or ts-node |
node dist/index.js |
| Type checking | On demand with tsc --noEmit |
During npm run build |
| Source | src/*.ts |
dist/*.js |
| Auto-restart | Yes, via watch mode | No, use a process manager |
| Dependencies | Dev dependencies included | Only production dependencies |
The table shows why the workflow differs. In development, speed and feedback matter. In production, stability and a small image matter. Keep the two modes separate with scripts, and never skip the build step before deploying.
Common Mistakes and Best Practices
- Forgetting
@types/node. Without it,process,__dirname, andfsare unknown to the compiler. Install it as a dev dependency so Node APIs are typed. - Setting
moduletoCommonJSin a modern project. This works but misses modern features and conflicts withNodeNext. Use"module": "NodeNext"for Node.js 18 and later, and include the.jsextension in relative imports. - Running
tsxorts-nodein production. These tools do not type-check fully and add runtime overhead. Build withtscand runnode dist/index.jsin production. - Editing files in
dist. The next build overwrites them. Always edit the.tssource and rebuild. Adddistto.gitignoreso it is never committed. - Skipping the build before deploy. If you deploy only source files or forget
npm run build,npm startfails becausedist/index.jsdoes not exist. Make the build a required step in your deploy script.
Real-World Example: A Typed Express API
This example combines the Node tsconfig.json, npm scripts, and a typed Express server with two routes.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
{
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc",
"start": "node dist/index.js"
}
}
import express from "express";
import type { Request, Response } from "express";
const app = express();
app.use(express.json());
app.get("/health", (_req: Request, res: Response) => {
res.json({ status: "ok" });
});
app.post("/echo", (req: Request, res: Response) => {
const { message } = req.body as { message?: string };
if (!message) {
res.status(400).json({ error: "message is required" });
return;
}
res.json({ echo: message });
});
app.listen(3000, () => {
console.log("API on http://localhost:3000");
});
// GET /health -> { "status": "ok" }
// POST /echo { "message": "hi" } -> { "echo": "hi" }
// POST /echo {} -> 400 { "error": "message is required" }
How it works, line by line. The tsconfig.json sets the Node-appropriate options so tsc writes to dist and checks strict types. The scripts map to tsx watch for development and node dist/index.js for production. In index.ts, express.json() parses JSON bodies. The /health route returns a simple JSON object. The /echo route reads req.body and casts it to { message?: string }. If message is missing, it returns a 400 with an error. Otherwise, it echoes the message. The early return after res.status(400) stops the handler so the success branch does not run. The app.listen callback confirms the server is up. Every handler is typed with Request and Response, so res.json, res.status, and req.body are checked by the compiler. This is a complete, deployable example of TypeScript with Node.js. The Modules & Namespaces tutorial explains the import rules that NodeNext enforces.
Summary
- TypeScript with Node.js gives you typed backends with autocomplete and fewer runtime bugs.
- Set up with
npm init, installtypescriptand@types/node, and add@types/expressfor Express. - A Node
tsconfig.jsonusestarget: ES2022,module: NodeNext,outDir: ./dist,rootDir: ./src, andstrict: true. - Keep
srcfor TypeScript anddistfor compiled output; never editdistby hand. - Add npm scripts for
devwithtsx watch,buildwithtsc, andstartwithnode dist/index.js. - In production, run the compiled
distfolder, because Node.js runs JavaScript, not TypeScript.
You have finished the TypeScript tutorial series. Return to the course index to review all 23 lessons, revisit any topic, and keep building with the type-safe patterns you have learned.
Frequently Asked Questions
Why do I need @types/node?
@types/node provides TypeScript definitions for Node.js built-in modules and globals like process, Buffer, and __dirname. Without it, the compiler treats these as unknown and reports errors. Install it as a dev dependency with npm install -D @types/node so your Node code type-checks correctly.
Should I use tsx or ts-node during development?
Both run TypeScript directly, but tsx is generally faster and handles modern module syntax without extra configuration. ts-node is older and may need flags for ESM. For new projects, tsx is the simpler choice. Remember that neither fully type-checks; run tsc --noEmit or your build script to catch type errors.
Why does Node.js not run my .ts file?
Node.js only understands JavaScript. It cannot parse TypeScript syntax like type annotations. You must compile .ts to .js with tsc, or use a runner like tsx that strips types before execution. In production, always run the compiled dist folder with plain node.
Do I need to install typescript in production?
No. The production server only runs JavaScript from dist. TypeScript, tsx, and ts-node are development tools. Install them as dev dependencies and use npm ci --omit=dev in deployment to skip them. This keeps the production image small and the startup fast.
What does module NodeNext mean in tsconfig?
module: NodeNext tells TypeScript to follow Node.js module rules. It supports both CommonJS and ES modules based on the file extension and package.json type. It also requires relative imports to include the final .js extension, even in .ts source files. This keeps your compiled output compatible with Node.js.
Practice Exercises
Exercise 1 (Easy): Set Up a Node TypeScript Project
Create a folder, run npm init -y, install typescript, @types/node, and tsx. Add a build script that runs tsc.
Show solution
mkdir demo-api
cd demo-api
npm init -y
npm install -D typescript @types/node tsx
{
"scripts": {
"build": "tsc",
"dev": "tsx watch src/index.ts",
"start": "node dist/index.js"
}
}
The setup installs the compiler and Node types as dev dependencies, and the scripts cover build, dev, and start.
Exercise 2 (Easy): Write a Node tsconfig.json
Create a tsconfig.json with target: ES2022, module: NodeNext, outDir: ./dist, rootDir: ./src, and strict: true.
Show solution
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
The module and moduleResolution values match Node.js rules, and outDir/rootDir keep source and output separate.
Exercise 3 (Medium): Typed Express Hello Route
Create src/index.ts with an Express server and a GET /hello route that returns { message: "Hello" }. Type Request and Response.
Show solution
import express from "express";
import type { Request, Response } from "express";
const app = express();
app.get("/hello", (_req: Request, res: Response) => {
res.json({ message: "Hello" });
});
app.listen(3000, () => {
console.log("Server on http://localhost:3000");
});
// GET /hello -> { "message": "Hello" }
The handler is typed with Request and Response, so res.json is checked and req properties are typed by @types/express.
Exercise 4 (Challenge): Build and Run the Compiled Output
Add a POST /echo route that validates a message field and returns it. Run npm run build, then npm start, and test both routes.
Show solution
import express from "express";
import type { Request, Response } from "express";
const app = express();
app.use(express.json());
app.post("/echo", (req: Request, res: Response) => {
const { message } = req.body as { message?: string };
if (!message) {
res.status(400).json({ error: "message is required" });
return;
}
res.json({ echo: message });
});
app.listen(3000, () => {
console.log("API on http://localhost:3000");
});
// POST /echo { "message": "hi" } -> { "echo": "hi" }
// POST /echo {} -> 400 { "error": "message is required" }
npm run build
npm start
The build writes dist/index.js, and npm start runs it with Node. The early return after the 400 stops the success branch, and the type cast on req.body keeps the access safe.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts.
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
