Backend Proxy Setup and Environment Variables

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.

Why environment variables?

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:

Project structure

your-project/
├── backend/
│   ├── .env
│   ├── server.js
├── frontend/
│   ├── vite.config.js
  

Backend setup using Express

Create a simple Express backend in the backend folder.

File: backend/server.js

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.

File: backend/.env

PORT=5000

We’ve stored the port number in a .env file, which gets loaded using the dotenv package.

Install backend dependencies

npm install express cors dotenv

Frontend proxy reminder

In your frontend’s vite.config.js, make sure you have:

server: {
  proxy: {
    "/api": "http://localhost:5000"
  }
}

Running your app

In two separate terminals, run:

Your frontend can now use:

fetch("/api/cats")
  .then(res => res.json())
  .then(data => console.log(data));

Why this matters

Using a proxy and environment variables means your project is:

Further exploration