DEV Community

Cover image for MERN TypeScript Setup Guide
Kafeel Ahmad (kaf shekh)
Kafeel Ahmad (kaf shekh)

Posted on

MERN TypeScript Setup Guide

Hello, Welcome to my guide on setting up a MERN stack project using TypeScript. This guide is designed to help both beginners and experienced developers to set up a fully functional development environment for MERN stack development.


Now, let’s get started with the setup.

Requirements

npm install -g typescript

Root

  1. Create a directory for your project with the following command:
mkdir my-app

2. Navigate to the directory:

cd my-app

3. Run the following command to initialize node in our directory.

Explanation: This command initializes a new Node.js project and creates a package.json file with default values.

npm init -y

Client

For the client, you can use either Vite or Create React App. Here are the instructions for both:

Using Vite

  1. On your root directory, type the following command:

Explanation: This command creates a new Vite application in a directory named client.

npx create-vite@latest client

2. You will see different options, select React.
3. Choose the option: TypeScript + SWC.
4. Once it finishes, use the following command to navigate to the client directory.

cd client

The following commands need to be run in the client directory.

5. Once in the client directory, run the following command to install all dependencies.

Explanation: This command installs the dependencies listed in the package.json file.

npm install

6. Once installed, navigate to the Project’s root directory using the following command:

cd ..

Using Create React App

  1. On your root directory, type the following command:

Explanation: This command creates a new Create React App application in a directory named client.

npx create-react-app client --template typescript

Server

  1. On your root directory, let’s create the server directory.

Explanation: This command creates a new directory named server.

mkdir server

2. Navigate to the server directory using the following command:

cd server

The following commands need to be run inside the server directory we’ve created.

3. Run this command to automatically create package.json file.

npm init -y

4. Now, run the following commands to install our dependencies.

Explanation: These commands install the necessary dependencies for our server. cors is used for enabling CORS, dotenv for loading environment variables, express for building the server, and mongoose for connecting to MongoDB. The development dependencies include TypeScript and the type definitions for our packages, as well as nodemon and ts-node for running our server during development.

npm install cors dotenv express mongoose
npm install -D typescript @types/express @types/cors @types/node nodemon ts-node

5. Create a .gitignore file and add the following lines to it:

Explanation: The .gitignore file specifies intentionally untracked files that Git should ignore.

node_modules
.env
dist/

6. Now, let’s setup TypeScript, create a file named tsconfig.json

Explanation: The tsconfig.json file is a configuration file for TypeScript. It specifies the root files and the compiler options to compile the project.

7. Copy and Paste the following configurations:

{
"compilerOptions": {
"target": "es2016",
"jsx": "preserve",
"module": "commonjs",
"allowJs": true,
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
"exclude": ["node_modules", "dist", "client"]
}

8. Create a directory named src inside your server directory using the following command:

mkdir src

The following commands need to be run inside the src directory we’ve created.

9. Create a file called server.ts

Explanation: This server.ts file sets up an Express server that connects to a MongoDB database and starts listening on a specified port.

10. Here’s a basic implementation of what the server.ts file should look like:

import express, { Express, Request, Response } from 'express';
import cors from 'cors';
import mongoose from 'mongoose';
import dotenv from 'dotenv';

dotenv.config();

const app: Express = express();

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

const uri: string =
process.env.MONGODB_URI || 'mongodb://localhost:27017/your-app';

(async () => {
try {
await mongoose.connect(uri);
console.log('Connected to the database');
} catch(error) {
console.error(error);
}
})();

app.get('/health', (_req: Request, res: Response) => {
res.status(200).send('Server is running');
});

const PORT: string | number = process.env.PORT || 3000;

app.listen(PORT, () => {
console.log(Server is running on PORT: <span>${PORT}</span>);
});

11. Let’s head back to the server directory using the following command:

cd ..

Explanation: This command changes the current directory to the parent directory.

The following content is for the server directory.

12. Now, let’s head over to our package.json file in the server directory.

13. Let’s add a command so that we can run nodemon with ts-node for our development.

14. Copy and paste this line on the script part of your package.json:

"scripts": {
"start": "ts-node src/server.ts",
"build": "tsc",
"dev": "nodemon src/server.ts"
},

15. Once this is done, let’s head over to the root directory with the following command:

cd ..

Running our project

The following content is for the project’s root directory

  1. Run the following command to install the development dependency concurrently.

Explanation: concurrently is a package that allows you to run multiple npm scripts concurrently (at the same time).

npm install --save-dev concurrently

2. Navigate to the package.json file in the root directory. This file contains metadata about your project and its dependencies.

3. Depending on the tool you used to create your client (either Vite or Create React App), copy the corresponding code block and paste it into the scripts section of your package.json file.

Vite

"scripts": {
"client": "cd client && npm run dev",
"server": "cd server && npm run dev",
"dev": "concurrently \"npm run server\" \"npm run client\""
},

Create React App

"scripts": {
"client": "cd client && npm run start",
"server": "cd server && npm run dev",
"dev": "concurrently \"npm run server\" \"npm run client\""
},

4. Now, let’s run our project using the following command:

npm run dev

5. Now, our client and server should be running concurrently. You should see the following output in your terminal:

[0] [nodemon] starting ts-node src/server.ts
[1]
[1] VITE v5.1.3 ready in 248 ms
[1]
[1] ➜ Local: http://localhost:5173/
[1] ➜ Network: use --host to expose
[0] Server is running on PORT: 3000
[0] Connected to the database

Top comments (0)