Tag: Express.js

Learn Express.js with beginner-friendly guides and tutorials. Explore the basics of routing, middleware, and building web apps using the popular Node.js framework.

  • Coding Interview Series – Intro to Express.js & Middleware

    Coding Interview Series – Intro to Express.js & Middleware

    While preparing for a coding interview, I found myself feeling a bit rusty on theoretical questions and scenarios I haven’t dealt with recently in my everyday work. After all, a developer doesn’t have to remember everything, right? Based on experience, a developer usually just remembers something exists — or has to look it up if they’ve never built anything similar.

    So what’s this post about? This — and others coming soon — will be part of a series covering questions I believe are important for any developer to know in order to feel confident going into an interview focused on Express.js. If you can answer these questions, you should feel pretty good. You won’t know everything, but you’ll be in solid shape to show your knowledge and tackle most of what comes your way.

    For me, these are basically my notes from preparing for coding interviews, and I figured I’d share them in case they help you too.

    We also plan to share a quiz app featuring these same questions in a simple, game-like environment. We’re building it now and will share it with you soon, so stay tuned!

    Enough said! Let’s start with some simple questions and gradually go deeper. In each post, I’ll also include links to the next parts of the series.

    Each answer in this series isn’t meant to be 100% complete or the final word. The goal is to show the interviewer that you understand the topic well and can explain it clearly. There’s always room for improvement or deeper discussion.

    Some questions include additional context to strengthen your understanding or explore the topic more deeply — we’ve marked those with a 🧠 icon.

    Others will point you to related resources for continued learning or best practices — those are marked with a 🚀 icon.

    Introductory coding interview questions

    What is Express.js?


    Express.js is a web application framework built on Node.js. It provides a higher-level API for handling HTTP requests. Express.js is commonly used to build REST APIs because it simplifies route handling compared to Node.js.

    What are some alternatives to Express.js?

    • Koa.js – Created by the same team behind Express
    • Fastify – Focuses on speed and performance
    • Nest.js – TypeScript-first framework

    Why should you use Express.js over Node’s built-in HTTP module?

    Node.js provides a low-level foundation, while Express abstracts common patterns, such as routing and middleware, making development faster and more maintainable.

    🧠 Deeper – Compare Express and Node Doing the Same Thing

    It’s easy sometimes to say something is different, but it would be nice to have a quick glimpse at an actual example. Because of this, below is a simple GET / users route implemented first with Express.js and then with plain Node.js so you can see the practical difference in code size and readability.

    // Express.js
    
    const express = require('express');
    const app = express();
    
    app.get('/users', (req, res) => {
      res.json({ message: 'Users list' });
    });
    
    app.listen(3000, () => console.log('Express server on port 3000'));
    JavaScript

    In Express.js if you use res.json() (or pass an object/array to res.send()), Express automatically sets the Content-Type header to application/json; charset=utf-8. You don’t need to call res.setHeader() yourself.

    // Node
    const http = require('http');
    
    const server = http.createServer((req, res) => {
      if (req.method === 'GET' && req.url === '/users') {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify({ message: 'Users list' }));
      } else {
        res.statusCode = 404;
        res.end('Not Found');
      }
    });
    
    server.listen(3000, () => console.log('Node server on port 3000'));
    JavaScript

    Middlewares

    What is middleware in Express?

    A middleware is a function. It runs before the final route handler, and it has access to the request, response, and next callback.

    An example of a middleware on a route level could be:

    // auth middleware
    function auth(req, res, next) {
      if (!checkAuthOfUserId(req.params.id)) {
        return res.status(403).send('Access denied');
      }
      next();
    }
    
    app.get('/users/:id', auth, (req, res) => {
      res.send(`Access granted to user ${req.params.id}`);
    });
    
    JavaScript

    How many types of middleware do you know?

    There are types of middleware:

    • Global
    • Path based
    • Route specific
    • Error handling

    Examples for each would be:

    Global type middleware example

    const express = require('express');
    
    const app = express();
    
    app.use(express.json());
    JavaScript

    This middleware will run for all incoming requests, regardless of route or method.

    Path-specific middleware example

    // middleware definition
    function adminLogger(req, res, next) { ... }
    
    // Apply middleware to all /admin paths (any method)
    app.use('/admin', adminLogger);
    
    app.get('/admin', (req, res) => {
      res.send('Admin Home');
    });
    
    app.post('/admin', (req, res) => {
      res.send('Admin POST');
    });
    
    app.get('/admin/settings', (req, res) => {
      res.send('Admin Settings');
    });
    JavaScript

    A path-specific middleware will run on all HTTP methods for any route that starts with that path.

    Route-based middleware example

    function requireAuth(req, res, next) { ... }
    
    app.get('/profile', requireAuth, (req, res) => {
      res.send('Welcome to your profile!');
    });
    JavaScript

    This middleware is applied only to a specific route and will run only when a GET request is made to the /profile endpoint.

    Error-handling middleware example

    Error-handling middleware is a special feature in Express.js that catches errors and handles them in a single location. It has four parameters:

    function errorHandler(err, req, res, next) {
      // Custom error handling logic
    }
    
    JavaScript

    In Express 5, if a route handler or middleware returns a Promise that is either rejected or throws an exception, Express will automatically call next(err) for you.

    What do you know about the app.use function?

    app.use() is a method in Express used to register middleware functions. These middleware run before any route handler and can modify the request or response, or end the response cycle.

    🚀 Further reading – Using the Right Terms — Path, Route, or Handler?

    When working with Express.js, you’ll frequently encounter the terms route, path, and handler. It’s important to understand the distinction between them, as each plays a different role in handling HTTP requests.

    Let’s break it down using the following example:

    app.get('/users', (req, res) => { ... });
    JavaScript

    Path: The URL pattern that the server listens to — here, it’s '/users'.

    Route: The combination of an HTTP method (e.g., GET, POST) and a path. In this example, GET /users is the route.

    Handler: The callback function that is executed when a request matches the route. In this case, it’s the function (req, res) => { ... }.

    Routes

    What is a route in Express.js?

    A route in Express defines a specific endpoint by combining an HTTP method (such as GET, POST, etc.) with a path, along with the logic (called a handler) that should execute when that request is received.

    Example

    app.get('/hello', (req, res) => {
      res.send('Hello this is route!')
    })
    JavaScript

    What’s the difference between app.get and app.post?

    Both app.get and app.post define routes.

    • app.get() handles GET requests for fetching data.
    • app.post() handles POST requests for updating or creating data.

    How would you retrieve a route param from a URL like /users/:id?

    app.get('/users/:id', (req, res) => {
      const { id } = req.params;
      res.send(`User id is ${id}`)
    })
    JavaScript

    What’s the difference between req.params, req.query, and req.body?

    Property
    Source
    Example
    req.params
    Route parameters
    /users/:id → req.params.id
    req.query
    URL query string
    /search?q=test → req.query.q
    req.body
    POST/PUT body
    req.body.name

    needs middleware like express.json()

    Can a route have multiple middleware functions? How?

    Yes, you could add middleware by adding it to the route before the handler.

    app.get('/secure', authMiddleware, loggingMiddleware, (req, res) => {
      res.send('Access granted');
    });
    JavaScript

    What is express.Router() and why would you use it?

    express.Router() creates a modular, mini Express app. It helps organize code by separating routes into files.

    For example, you might organize all your user-related routes in a separate file, such as:

    // routes/users.js
    
    const express = require('express');
    const router = express.Router();
    
    // GET /users
    router.get('/', (req, res) => {
      res.send('User list');
    });
    
    // GET /users/:id
    router.get('/:id', (req, res) => {
      res.send(`User ID: ${req.params.id}`);
    });
    
    module.exports = router;
    JavaScript

    and then import and register them in your main Express application file like this:

    const express = require('express');
    const app = express();
    
    const userRoutes = require('./routes/users');
    
    // Mount user router at /users
    app.use('/users', userRoutes);
    
    app.listen(3000, () => console.log('Server running'));
    JavaScript

    What’s next?

    In this post, we reviewed key Express.js concepts — from routing and middleware types to error handling. These are the kinds of topics that come up often in coding interviews.

    In the next part of this series, we’ll shift gears toward project-level questions. Stay tuned!

  • How to Restart Your Node App Without Nodemon

    If you’ve built anything with Node.js, you’ve probably used nodemon to automatically restart your app when files change. It’s been a go-to developer tool for years — but did you know you no longer need it?

    With Node.js 18.11 and above, there’s a built-in --watch option. It tells Node to monitor your source files and automatically restart the process when changes are detected.

    node --watch app.js
    Bash

    That’s it. No configuration, no dependencies, no waiting for external tools to kick in.

    It works great when:

    • You’re building small or medium apps.
    • You don’t need advanced features like custom delay or file filters.
    • You want to keep your environment minimal and lean.

    Keep in mind that, large projects with complex file structures might still benefit from nodemon or more advanced tools.

  • How To Setup An Express.js Server Using Typescript (2024)

    How To Setup An Express.js Server Using Typescript (2024)

    This post describes all the necessary steps to set up an Express.js server using Typescript. We’ll start our project from scratch, create an Express.js server using Vanilla Javascript, and then convert our project to support Typescript. Let’s dive in!

    Technology stack used

    • npm10.8.2
    • node20.15.1
    • express.js4.19.2
    • typescript5.5.3

    Setting Up the Project with Express.js

    In an empty folder of your choice, run the npm initializer with all default options selected by using the following command:

     
    npm init --yes  # or npm init -y
    
    Bash

    By using the --yes flag we ask npm to set the default answer to any question asked during setup. Remove the --yes flag to see the questions I am referring to.

    We will be using a folder called server-project for this post. Running the previous command is the first step of our project, resulting in a package.json file with the following content:

    package.json
    {
      "name": "server-project",
      "version": "1.0.0",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "description": ""
    }
    
    
    JSON

    Now that we have initialized our project using npm let’s install Express.js:

    
    npm install [email protected]
    
    Bash

    By doing so, Express.js will be added to the package.json file’s dependencies.

    package.json
    {
      "name": "server-project",
      "version": "1.0.0",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "description": "",
      "dependencies": {
        "express": "^4.19.2"
      }
    }
    
    
    JSON

    The next step is to set up a basic server following Express’s documentation

    Create a new file in your project folder, named index.js, and inside that file, add

    index.js
    const express = require('express');
    const app = express();
    
    const port = 3004;
    
    app.get('/', (req, res) => {
      res.send('Hello World!');
    })
    
    app.listen(port, () => {
      console.log(`Example app listening on port ${port}`);
    });
    
    JavaScript

    Excellent! Using node we get to see this baby up and running!

    node index.js
    Bash

    Executing this to your terminal will show you

    Example app listening on port 3004
    
    Bash

    Opening localhost:3004 to your browser, you will see our server’s response.

    Browser showing basic express server "Hello World"reponse

    In any case, you get some kind of error like listen EADDRINUSE: address already in use :::3004 it means that you are running another application in the port 3004. To fix this, either change in the index.js file, this app’s port, to e.g 3001 or kill the other app you already are running on port 3004.

    Installing Typescript

    Now that we have successfully installed our Express.js server and we see that everything is working as expected, it’s time to add Typescript.

    Kill the node script using Ctrl + C and install Typescript by running

    npm install --save-dev [email protected]
    Bash

    Typescript is stored as a development dependency because it is used only in the development phase of a project for transpiling TS code to Javascript. In production environments, browsers and servers are capable of interpreting and executing JavaScript, not Typescript code.

    package.json
    {
      "name": "server-project",
      "version": "1.0.0",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "description": "",
      "dependencies": {
        "express": "^4.19.2"
      },
      "devDependencies": {
        "typescript": "^5.5.3"
      }
    }
    
    JSON

    After installing Typescript to our project we need to initialize it by typing

    npx tsc --init
    Bash

    --init flag is used to initialize a TS project and create a tsconfig.json file with the default options set.

    But what about tsc and npx? Where did these come from?

    Understanding tsc and npx: Why do we use them?

    tsc is the command line tool used by Typescript to compile code (tsc 👉 typescript compiler) into Javascript. It is a part of Typescript package, and it became available to our system when we installed Typescript.

    npx on the other side is a package runner tool that came with npm. It was released from npm version 5.2.0. This tool is useful in cases where:

    • We want to run a package without installing it
    • We will be executing a package using different versions
    • To avoid global installation of a package

    Ok, sure, but in our case, since we have Typescript installed in our local project folder, and because of this, we also have tsc installed, then why not just use tsc --init? Right? Why do we want to use npx to run tsc?

    Just using tsc might use a global version of Typescipt and not the local one

    That question killed some of my brain cells 🧠 before figuring it out 😅. Just using tsc --init may use a global version of Typescript installed on your computer. Using npx tsc --init instead will make sure that you are using the local version of tsc package. This way, you will avoid any surprises because of different package versions. 🥳

    After successfully executing npx tsc --init you will see a tsconfig.json file created with the following content

    tsconfig.json
    {
      "compilerOptions": {
        /* Visit https://aka.ms/tsconfig to read more about this file */
    
        /* Projects */
        // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental ompilation of projects. */
        // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
        // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
        // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
        // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
        // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */
    
        /* Language and Environment */
        "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
        // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
        // "jsx": "preserve",                                /* Specify what JSX code is generated. */
        // "experimentalDecorators": true,                   /* Enable experimental support for legacy experimental decorators. */
        // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
        // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
        // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
        // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
        // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
        // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
        // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
        // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */
    
        /* Modules */
        "module": "commonjs",                                /* Specify what module code is generated. */
        // "rootDir": "./",                                  /* Specify the root folder within your source files. */
        // "moduleResolution": "node10",                     /* Specify how TypeScript looks up a file from a given module specifier. */
        // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
        // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
        // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
        // "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */
        // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
        // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
        // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
        // "allowImportingTsExtensions": true,               /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
        // "resolvePackageJsonExports": true,                /* Use the package.json 'exports' field when resolving package imports. */
        // "resolvePackageJsonImports": true,                /* Use the package.json 'imports' field when resolving imports. */
        // "customConditions": [],                           /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
        // "resolveJsonModule": true,                        /* Enable importing .json files. */
        // "allowArbitraryExtensions": true,                 /* Enable importing files with any extension, provided a declaration file is present. */
        // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
    
        /* JavaScript Support */
        // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
        // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
        // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
    
        /* Emit */
        // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
        // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
        // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
        // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
        // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
        // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
        // "outDir": "./",                                   /* Specify an output folder for all emitted files. */
        // "removeComments": true,                           /* Disable emitting comments. */
        // "noEmit": true,                                   /* Disable emitting files from a compilation. */
        // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
        // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
        // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
        // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
        // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
        // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
        // "newLine": "crlf",                                /* Set the newline character for emitting files. */
        // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
        // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
        // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
        // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
        // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    
        /* Interop Constraints */
        // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
        // "verbatimModuleSyntax": true,                     /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
        // "isolatedDeclarations": true,                     /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
        // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
        "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
        // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
        "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */
    
        /* Type Checking */
        "strict": true,                                      /* Enable all strict type-checking options. */
        // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */
        // "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */
        // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
        // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
        // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
        // "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
        // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
        // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
        // "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */
        // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */
        // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
        // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
        // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
        // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
        // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
        // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
        // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
        // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */
    
        /* Completeness */
        // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
        "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
      }
    }
    
    JSON
    Expand

    Refactoring JavaScript to TypeScript

    Now that we have successfully installed and initialized Typescript we need to start writing some Typescript to have fun.

    First of all let’s rename our index.js file to index.ts. If we don’t do that and we run our tsc compiler we will see an error

    error TS18003: No inputs were found in config file 'server-project/tsconfig.json'. Specified 'include' paths were '["**/*"]' and 'exclude' paths were '[]'.
    
    Bash

    because we have no .ts files in our project.

    Make sense right? After all we need at least .ts one file to start our TS journey. Ok now that we have renamed it, lets, out of curiosity, run npx tsc and see what happens. By running this command, I get the following errors

    index.ts:1:17 - error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
    
    1 const express = require('express');
                      ~~~~~~~
    
    index.ts:6:15 - error TS7006: Parameter 'req' implicitly has an 'any' type.
    
    6 app.get('/', (req, res) => {
                    ~~~
    
    index.ts:6:20 - error TS7006: Parameter 'res' implicitly has an 'any' type.
    
    6 app.get('/', (req, res) => {
                         ~~~
    
    Bash

    It seems the compiler is unable to successfully convert our .ts file to .js due to three issues. We need to address these issues one at a time. A guide is available that describes each error in detail, including their causes and solutions. Feel free to check it out if you want to learn more.

    After dealing with all the necessary problems, the updated .ts file should look something like

    index.ts
    import express, { Express, Request, Response } from 'express';
    
    const app: Express = express();
    
    const port = 3004;
    
    app.get('/', (req: Request, res: Response) => {
      res.send('Hello World!');
    })
    
    app.listen(port, () => {
      console.log(`Example app listening on port ${port}`);
    });
    
    
    TypeScript

    Now that we have everything fixed let’s run npx tsc to see if there is anything left. Running this command showed nothing in my terminal. Which is a good sign. To see the compilation results though, I need to make two small tweaks.

    Configure TypeScript to create a new folder for all compiled files by using the outDir compiler option.

    tsconfig.json
    {
      "compilerOptions": {
        // ....
        "outDir": "./dist",
        // Specify an output folder for all emitted files.
      }
    }
    
    JSON

    Rename the package.json main file and add a compilation Script

    package.json
    {
      "name": "server-project",
      "version": "1.0.0",
      "main": "dist/index.js",
      "scripts": {
        "start": "npx tsc && node dist/index.js",
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "description": "",
      "dependencies": {
        "express": "^4.19.2"
      },
      "devDependencies": {
        "@types/express": "^4.17.21",
        "@types/node": "^22.1.0",
        "typescript": "^5.5.4"
      }
    }
    
    
    JSON

    Superb! Now we have everything we need. What’s next? A victory dance! When you run npm start, your terminal will display “Example app listening on port 3004,” which means we did it!

    Example app listening on port 3004
    Bash