Today, I will give step-by-step instructions on how to deploy a MERN project to Vercel, with the frontend and backend deployed separately.
1. Create Project Directory:
mkdir mernproject
cd mernproject
2. Initialize Node Project:
npm init -y
3.Install Express:
npm install express
4. Install Other Necessary Packages for Backend:
npm install cors body-parser dotenv mongoose
5. Create .env File:
touch .env
- Add your tokens and other sensitive information in this file.
6. install Nodemon:
npm install --save-dev nodemon
- This will automatically restart your project when you save.
7.Create Server File:
touch server.js
8.Set Up React:
npx create-react-app client
- Replace
client
with the name of the folder you want your frontend to be in. In this case, I useclient
.
9. Build Frontend:
- when you are done coding and it's time to deploy:
cd client
npm build
git add .
git commit -m "Build frontend"
git push origin main
10. Deploy Frontend to Vercel:
If you have already initialized Vercel with GitHub, you will see your project in Vercel.
Import your project in Vercel.
11.Copy Frontend Link:
- Copy the link generated by Vercel.
12 Update Backend:
app.use(
cors({
origin: 'frontend link',
})
);
13.Deploy Backend to Vercel:
- At the root of your project, create a vercel.json file and add the following code inside:
{
"version": 2,
"builds": [{ "src": "server.js", "use": "@vercel/node" }],
"routes": [{ "src": "/(.*)", "dest": "server.js" }]
}
This will tell Vercel the entry point of your project. If the entry point is not server.js, replace server.js with the entry point of your server.
Create a .gitignore file:
touch .gitignore
Add
node_modules
,.env
, andfrontend-folder
to.gitignore
.Ensure your frontend folder is in
.gitignore
because you don't need to deploy that again.
14. Push to GitHub and Upload to Vercel:
- Push your folder to GitHub and upload to Vercel.
15. Set Environment Variables in Vercel:
Go to your project directory in Vercel, click on settings, click on environment variables, import your
.env
file, and save.Make sure you're in your imported backend directory after successfully uploading before uploading the variables.
After these steps, your project will work perfectly as it does in development mode.