Now that you've set up a frontend proxy using Vite, let’s create a simple backend to receive requests and learn how to use environment variables for flexible configuration.
Imagine your backend is a food truck. In development, it's parked in your driveway, and in production, it moves to a busy downtown corner. Rather than hardcoding the location (port, database, keys) into the truck, you use a GPS (environment variable) that tells it where to go depending on the situation.
Environment variables let you define flexible and secure configurations — especially helpful for:
your-project/
├── backend/
│ ├── .env
│ ├── server.js
├── frontend/
│ ├── vite.config.js
Create a simple Express backend in the backend folder.
import express from "express";
import cors from "cors";
import dotenv from "dotenv";
dotenv.config();
const app = express();
const PORT = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.get("/api/cats", (req, res) => {
res.json([
{ name: "Whiskers", age: 2 },
{ name: "Socks", age: 5 }
]);
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
This server listens for GET requests at /api/cats and sends back a list of cats as JSON.
PORT=5000
We’ve stored the port number in a .env file, which gets loaded using the dotenv package.
npm install express cors dotenv
In your frontend’s vite.config.js, make sure you have:
server: {
proxy: {
"/api": "http://localhost:5000"
}
}
In two separate terminals, run:
node backend/server.js (or use nodemon)npm run dev inside the frontend folderYour frontend can now use:
fetch("/api/cats")
.then(res => res.json())
.then(data => console.log(data));
Using a proxy and environment variables means your project is:
dotenv in production with build tools like PM2.env.development and .env.production files for custom setupsprocess.env.NODE_ENV for behavior togglingmorgan for backend visibility