Hosting a React Vite Application on EC2 with PM2 in Development Mode


Hosting a React Vite Application on EC2 with PM2 in Development Mode

Developing and testing React applications is often done in a local environment, but there are scenarios where you might want to run your application on a remote server for testing or collaboration. This guide will walk you through the process of hosting a React Vite application on an EC2 instance using PM2 in development mode.

Prerequisites

Before you begin, make sure you have the following:

  • An AWS account with an EC2 instance.

  • Node.js and npm installed on your EC2 instance.

  • PM2 installed globally on your EC2 instance.

Step 1: Create a React Vite Application

If you don't have a React Vite application, create one using the following steps:

npx create-vite my-react-app --template react
cd my-react-app

Step 2: Modify Vite Development Script

By default, the Vite development server only listens on localhost, making it inaccessible externally. To allow external access, modify the scripts section in your package.json file:

"scripts": {
  "dev": "vite --host 0.0.0.0"
}

Save the changes.

Step 3: Install Dependencies

Install the dependencies required for your Vite application:

npm install

Step 4: Start the Vite Development Server

Start the Vite development server with PM2:

pm2 start npm --name "my-react-app" -- run dev

Replace "my-react-app" with the desired name for your PM2 process.

Step 5: Access Your React Vite Application

Check the PM2 logs to get the external access information:

pm2 logs

Look for the output similar to the following:

1|my-react |   Local:   http://localhost:3000/
1|my-react |   Network: http://your-local-ip:3000/
1|my-react |   Network: http://18.218.93.142:3000/

Access your Vite app externally by visiting http://18.218.93.142:3000 in your web browser.

Conclusion

Running a React Vite application on an EC2 instance using PM2 in development mode provides a convenient way to test and collaborate on your application. Keep in mind that exposing the development server to the public internet is suitable for testing purposes but not recommended for production. In production, you would typically build your app (npm run build) and serve the optimized output using a production-ready server.

Happy coding!

Did you find this article valuable?

Support Itanand's Blog by becoming a sponsor. Any amount is appreciated!