Setting Up An Express.js Server With TypeScript

Setting Up An Express.js Server With TypeScript

ยท

3 min read

We know how to set up an express server with JavaScript, but some of us find it difficult to set up with TypeScript ๐Ÿ˜ช.

C'mon man, let's grab a cup of coffee, hot one โ˜•

Here are some steps in which an express server can be set up TypeScript :

  1. Create a new nodejs project using npm init -y

  2. Install TypeScript and required dependencies using npm install --save-dev typescript ts-node nodemon

  3. Initialize TypeScript by running tsc --init . This will create a tsconfig.json file in the root directory of your project.

  4. Modify the tsconfig.json in the "compilerOptions", with the following options:

    • "module": "NodeNext" - Specifies the module code generation method.

    • "moduleResolution": "node" - Helps the compiler figure out what an import refers to. The value node mimics the Node module resolution mechanism.

    • "baseUrl": "src" - Specifies the base directory for resolving non-relative module names.

    • "outDir": "dist" - Specifies the output directory for compiled files.

    • "sourceMap": true - Generate source maps for better debugging.

    • "noImplicitAny": true - Raises an error when a variable or parameter has an implicit any type.

    • "esModuleInterop": true - Enables compatibility with libraries that use export= .

    • "include": ["src/**/*"] - Specifies the files or directories to include in the compilation process.

  5. Create a file called nodemon.json with the following configuration:

         {
           "watch": ["src"],
           "ext": ".ts,.js",
           "exec": "ts-node ./src/index.ts"
         }
    

    This tells nodemon to watch the src directory for changes with .ts and .js extensions and execute the index.ts file using ts-node.

  6. Create a new folder called src and add an index.ts file inside it. This file will contain the code for your Express.js server.

  7. Install express and other required middleware using npm install express body-parser cookie-parser compression cors.

  8. Install type definitions for the middleware using npm install @types/express @types/body-parser @types/cookie-parser @types/compression @types/cors .

  9. Modify the scripts section in package.json to include the following:

         "scripts": {
             "start": "nodemon",
             "test": "echo \"Error: no test specified\" && exit 1"
         }
    

    This tells npm to run nodemon when you run npm start.

  10. Add the code for your Express.js server in src/index.ts. Let's build a simple server

    // Import necessary libraries and modules
    import express, {Application, Request, Response, NextFunction} from 'express';
    import bodyParser from 'body-parser';
    import cookieParser from 'cookie-parser';
    import compression from 'compression';
    import cors from 'cors';
    
    // Create an instance of the Express application
    const app: Application = express();
    
    // Use middleware to parse request bodies, cookies, compress response data, and enable CORS
    app.use(bodyParser.json());
    app.use(cookieParser());
    app.use(compression());
    app.use(cors());
    
    // Define a route handler for the root path
    app.get('/', (req: Request, res: Response) => {
        res.send('Hello World!');
    });
    
    // Define an error handling middleware
    app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
        console.log(error);
        next();
    });
    
    // Set the port number for the server
    const PORT: number = process.env.PORT || 3000;
    
    // Start the server and listen for incoming requests on the specified port
    app.listen(PORT, () => {
        console.log(`Server running on port ${PORT}`);
    });
    
  11. Run your server using npm start.

Yay! ๐Ÿฅณ๐Ÿฅณ .We have successfully set up an express server with TypeScript.

Have a nice day creating a bug less environment for your APIs ๐Ÿ‘‹

ย