This post will go from scratch to set up React and NodeJS in TypeScript. We will send a response from the server to the client.

Step 1: Decide a project folder

Open the command prompt where you want to place your project. Right now, I am opening the command prompt on my desktop. I will put my project on a Desktop. I will rename my project folder as React-Node-TypeScript for now. You can choose the project folder name by yourself.

mkdir React-Node-TypeScript

Step 2: Change the directory to that folder

cd React-Node-TypeScript

Step 3: Open Visual Studio Code

code .

Now you can use the VS code terminal to write the command. Open terminal with Ctrl + backtick (`)

Step 4: Make two directories for client and server

mkdir client, server

Step 5: Set up Server

cd server
npm init -y

This will create a package.json file in a server directory.

Install required packages:

npm install express @types/express typescript ts-node-dev nodemon cors @types/cors  

Now create the src directory; inside the src, create the index.ts file below.

mkdir src

Create an index.ts file in the src directory and write the initial code as below:

// index.ts
import cors from "cors";
import express from "express";

const app = express();
const PORT = 5000;

// Enable CORS for all routes
app.use(cors());

app.get("/", (req, res) => {
  res.send("Hello from Server!");
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Create a tsconfig.json file to configure TypeScript compilation:

npx tsc --init

Edit the tsconfig.json file to specify the src directory as the root directory. Also, look for outdir and set it to the dist folder. All your compiled js code will be placed in this folder.

{
  "compilerOptions": {
     .......
    "outDir": "./dist",   
  },
  "include": ["src/**/*"]
}

Edit the package.json file to include the start script. As we have already installed nodemon, we don't need to restart the server if we change anything on the code.

"scripts": {
    "start": "npx tsc && nodemon ./src/index.ts"
}

Create a .gitignore file on the server side and add a path of a file that you don't want to track by the version controller.

/node_modules
/dist

Now everything is set. You can start the server.

npm start

You will get a message like 'Server is running on port 5000' which indicates your server is successfully running.

Don't close the terminal. Keep your server running. Open another new terminal. Now we will set up the client side.

Step 6: Set up the client

Make sure you are in the root directory. In my case, it is React-Node-TypeScript.

cd client
npx create-react-app . --template typescript

It may take a little bit of time. It will set up the initial react code. Now we will make changes on our own.

First, remove the .git folder from the client directory, we can track the client and server folders from the root directory.

Start the client project.

npm start

Your client application will run in port 3000 if not already used.

Now you can open another new terminal and keep the client running.

Make sure you are in the client folder. Install the Axios library.

npm install axios

Create a utils folder in the src directory, then create a http.ts file and add the below code.

// http.ts
import axios from "axios";

const http = axios.create({
  baseURL: "http://localhost:5000", // assuming your Node.js server is running on port 5000
});

export const fetchMessage = async (): Promise<string> => {
  const response = await http.get("/");
  return response.data;
};

Now update the App.tsx file. Replace with the following code.

import "./App.css";
import { fetchMessage } from "./utils/http";
import React, { useEffect, useState } from "react";

function App() {
  const [message, setMessage] = useState<string>("");

  useEffect(() => {
    const fetchData = async () => {
      try {
        const data = await fetchMessage();
        setMessage(data);
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    };

    fetchData();
  }, []);

  return <div className="App">{message}</div>;
}

export default App;

You can remove all the default styling. Clear App.css and index.css

Check your application. The message should display 'Hello from Server!' coming from the server.

Congratulations, you have successfully set up the React and NodeJS project in typescript.

Make sure your folder structure looks something like this.

React-Node-TypeScript/
├── client/
│   ├── public/
│   │   ├── index.html
│   │   └── ...
│   ├── src/
│   │   ├── utils
│   │   ├── ├── http.ts
│   │   ├── App.css
│   │   ├── App.tsx
│   │   ├── index.css
│   │   ├── index.tsx
│   │   └── ...
│   ├── package.json
│   ├── tsconfig.json
│   └── ...
├── server/
│   ├── dist/
│   ├── src/
│   │   ├── index.ts
│   │   └── ...
│   ├── package.json
│   ├── tsconfig.json
│   └── ...