Project Structure for MEVN Apps
By the end of this lesson you will know where every file of a MEVN app lives and why, which environment variables each half reads, what the JSON contract between Vue and Express looks like, and the naming and code style rules this course follows. Every later lesson adds files to this exact layout, so keep this page open as a map.
What you should know first: Set Up Your MEVN Environment, where you created the client/ and server/ folders. For bigger front-end layouts see Project Structure at Scale, and for bigger back ends see Structuring a Real-World API. Here we keep things just big enough for NoteNest.
Two halves, two packages
A MEVN project is really two programs that talk over HTTP. The Vue client is a set of files that a browser downloads. The Express server is a process that runs all the time. They have different dependencies, different build steps and, in production, often different hosts. So each half gets its own folder with its own package.json.
Think of a wedding caterer in Lucknow. The kitchen and the serving counter work together, but each keeps its own stock register. Sugar for the kitchen is not mixed up with paper plates for the counter. If the counter moves to another hall, the kitchen does not have to change. The client/ and server/ folders work the same way.
The root folder holds only what both halves share: the Git repository, one .gitignore, a README and a small package.json whose dev script starts both halves at once.
The final NoteNest layout
This is the layout the whole course uses. Files marked "later" do not exist yet; the lesson that adds them is named in the comment.
notenest/
├── package.json root scripts: "dev" starts both halves
├── .gitignore node_modules/, dist/, .env
├── README.md
├── client/ Vue 3 + Vite (runs in the browser)
│ ├── package.json
│ ├── index.html
│ ├── vite.config.js dev proxy: /api -> http://localhost:3000
│ ├── .env.example VITE_API_URL=/api
│ ├── public/
│ └── src/
│ ├── main.js creates the app, adds Pinia and the router
│ ├── App.vue
│ ├── api/ client.js (fetch wrapper), notes.js
│ ├── components/ NoteCard.vue, TagFilter.vue (later)
│ ├── views/ NotesView.vue, NoteDetailView.vue (later)
│ ├── router/ index.js
│ └── stores/ notes.js, auth.js (later, Pinia)
└── server/ Express 5 + Mongoose (runs on Node.js)
├── package.json
├── .env real settings, never committed
├── .env.example the same keys with safe sample values
└── src/
├── server.js connects to MongoDB, then starts listening
├── app.js builds the Express app (exported for tests)
├── config.js reads and checks environment variables
├── db.js connectDB() (MongoDB lesson)
├── seed.js sample notes for development (MongoDB lesson)
├── models/ Note.js, User.js (later)
├── routes/ notes.js, auth.js (later)
└── middleware/ errors.js, auth.js (later)Delete the sample client/src/stores/counter.js that create-vue added. The real notes store arrives in State Management with Pinia.
The server: one job per file
Keeping one job per file makes each piece easy to find and easy to test.
config.js is the only file that reads process.env. It checks the required values once, at startup, and fails with a clear message instead of crashing later with a confusing one.
// server/src/config.js
// Reads settings from environment variables once, and fails fast if one is missing.
const required = ['MONGODB_URI', 'CLIENT_ORIGIN']
const missing = required.filter((name) => !process.env[name])
if (missing.length > 0) {
throw new Error(`Missing environment variables: ${missing.join(', ')}`)
}
export const config = {
port: Number(process.env.PORT ?? 3000),
mongodbUri: process.env.MONGODB_URI,
clientOrigins: process.env.CLIENT_ORIGIN.split(','),
isProduction: process.env.NODE_ENV === 'production',
}Start the server without a .env file and you see the problem at once (after a few lines that point at config.js):
Error: Missing environment variables: MONGODB_URI, CLIENT_ORIGIN
app.js builds the Express app and exports it, but does not start it. server.js imports the app and calls listen(). Why split them? Tests (in Testing the MEVN App) can import app and send it fake requests without opening a real port. You will write app.js in the next lesson. Here is server.js as it looks for now:
// server/src/server.js
import app from './app.js'
import { config } from './config.js'
app.listen(config.port, (error) => {
if (error) throw error
console.log(`NoteNest API listening on http://localhost:${config.port}`)
})In Express 5 the listen() callback receives an error if the port cannot be opened, so the if (error) line turns a busy port into a clear crash. The MongoDB lesson adds one line above app.listen to connect to the database first.
The client: one door to the API
On the Vue side, the most important rule is: components never call fetch directly. All HTTP code lives in src/api/. client.js knows the base URL and the error shape. notes.js has one small function per endpoint.
// client/src/api/client.js
// The only file that knows where the API lives.
const BASE_URL = import.meta.env.VITE_API_URL ?? '/api'
export async function apiRequest(path, options = {}) {
const res = await fetch(`${BASE_URL}${path}`, {
...options,
headers: { 'Content-Type': 'application/json', ...options.headers },
})
const data = await res.json().catch(() => null)
if (!res.ok) {
throw new Error(data?.error?.message ?? `Request failed with status ${res.status}`)
}
return data
}// client/src/api/notes.js
import { apiRequest } from './client.js'
export function listNotes(tag) {
const query = tag ? `?tag=${encodeURIComponent(tag)}` : ''
return apiRequest(`/notes${query}`)
}
export function getNote(id) {
return apiRequest(`/notes/${encodeURIComponent(id)}`)
}
export function createNote(note) {
return apiRequest('/notes', { method: 'POST', body: JSON.stringify(note) })
}If the API moves, or the error shape changes, you edit one file instead of twenty components. encodeURIComponent makes sure a tag such as c++ or exam & fees reaches the server as one value. The @/ alias that create-vue set up means a component can write import { listNotes } from '@/api/notes.js' from any folder depth.
The page below runs the real apiRequest function against a pretend server that answers with the same status codes and JSON as the NoteNest API. Watch how one function turns every answer into either data or a readable error.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>apiRequest against a pretend API</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
pre { background: #f4f4f4; padding: 10px; white-space: pre-wrap; }
</style>
</head>
<body>
<h1>One door to the API</h1>
<pre id="log"></pre>
<script>
// A pretend server with the same answers as the NoteNest API
function reply(status, body, type = "application/json") {
const text = type === "application/json" ? JSON.stringify(body) : body;
return new Response(text, { status, headers: { "Content-Type": type } });
}
async function fakeFetch(url, options = {}) {
const method = options.method ?? "GET";
if (url === "/api/notes" && method === "GET") {
return reply(200, { notes: [{ id: "1", title: "DBMS viva questions", tags: ["college"], pinned: true }] });
}
if (url === "/api/notes" && method === "POST") {
const input = JSON.parse(options.body);
if (!input.title) return reply(400, { error: { code: "VALIDATION_ERROR", message: "Title is required" } });
return reply(201, { note: { id: "3", ...input } });
}
if (url.startsWith("/api/notes/")) {
return reply(404, { error: { code: "NOT_FOUND", message: "Note not found" } });
}
return reply(502, "<h1>Bad Gateway</h1>", "text/html");
}
// client/src/api/client.js, with fetch swapped for fakeFetch
const BASE_URL = "/api";
async function apiRequest(path, options = {}) {
const res = await fakeFetch(`${BASE_URL}${path}`, {
...options,
headers: { "Content-Type": "application/json", ...options.headers }
});
const data = await res.json().catch(() => null);
if (!res.ok) {
throw new Error(data?.error?.message ?? `Request failed with status ${res.status}`);
}
return data;
}
const log = document.querySelector("#log");
async function attempt(label, path, options) {
try {
const data = await apiRequest(path, options);
log.textContent += `${label}: OK ${JSON.stringify(data)}\n`;
} catch (err) {
log.textContent += `${label}: ERROR ${err.message}\n`;
}
}
(async () => {
await attempt("List notes", "/notes");
await attempt("Create good note", "/notes", { method: "POST", body: JSON.stringify({ title: "Pay hostel fees" }) });
await attempt("Create empty note", "/notes", { method: "POST", body: JSON.stringify({ body: "no title" }) });
await attempt("Missing note", "/notes/9");
await attempt("Unknown path", "/reports");
})();
</script>
</body>
</html>The last line is the interesting one. The pretend server answered with an HTML error page, so res.json() failed, data became null, and the user still gets a sensible message: "Request failed with status 502".
Environment variables on both sides
An environment variable is a named setting that the operating system or hosting service gives to a program, outside the code. You change it per machine (your laptop, a test server, production) without editing files in Git. If you are new to them, read process & Environment Variables.
| Name | Side | Example value | Secret? |
|---|---|---|---|
PORT | server | 3000 | No |
MONGODB_URI | server | mongodb://127.0.0.1:27017/notenest | Yes, once it holds a password |
CLIENT_ORIGIN | server | http://localhost:5173 (comma-separated for several) | No |
NODE_ENV | server | production on the live server | No |
JWT_SECRET | server | added in the login lesson | Yes |
VITE_API_URL | client | /api | Never put secrets here |
The real values go in server/.env, which Git ignores. A copy with safe sample values, server/.env.example, is committed so a new teammate knows which keys to fill in.
The API contract and the error shape
These rules hold for every NoteNest endpoint, now and in later lessons:
- Every API path starts with
/api, and resources use plural nouns:/api/notes,/api/notes/:id. - Requests and responses are JSON. A list comes wrapped in a named key,
{ "notes": [...] }, and a single item as{ "note": {...} }. Wrapping leaves room to addpageortotallater without breaking the client. - Each note has an
idstring. The server converts MongoDB's_idbefore sending, so the client never deals with_id. - Status codes carry meaning:
200OK,201created,204deleted with no body,400bad input,401not logged in,403not allowed,404not found,500server fault. - Every error, from every route, has the same shape:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Title is required"
}
}code is for programs (Vue can check NOT_FOUND), and message is a sentence safe to show users. A 500 error never includes a stack trace or database details; those go to the server log only.
Naming and code style
| Thing | Rule | Example |
|---|---|---|
| Modules | ES modules in both halves ("type": "module") | import express from 'express' |
| Formatting | 2 spaces, single quotes, no semicolons, lines up to 100 characters (create-vue's Prettier settings) | const port = 3000 |
| Vue components | PascalCase, at least two words | NoteCard.vue |
| Route-level components | PascalCase ending in View | NotesView.vue |
| Pinia stores | use + name + Store, file named after the resource | useNotesStore in stores/notes.js |
| Mongoose models | Singular PascalCase, one per file | Note in models/Note.js |
| Other files | lowercase | routes/notes.js, api/client.js |
| JSON fields | camelCase | createdAt, pinned |
| Ports | API on 3000, Vite on 5173 |
The "two words" rule for components comes from the official Vue style guide: it avoids clashes with real HTML element names, so NoteCard is fine and Card is not.
Common mistakes
- Installing server packages in the client folder (or the other way round). Run
npm installinside the folder that will use the package. Express insideclient/package.jsonis a sign something went wrong. - Calling
fetchfrom inside components. URLs and error handling get copied everywhere. Keep them insrc/api/. - Reading
process.envall over the server. A typo such asprocess.env.MONGO_URIsilently givesundefined. Read everything inconfig.js. - Committing
.env. Add.envto.gitignorebefore you create the file. If a secret was ever committed, change the secret, because Git history keeps it. - Different error shapes per route. One route sends
{ message }, another sends plain text, and the client breaks. Use one shape everywhere.
Interview questions
1. Why keep the client and server in separate folders with separate package.json files?
They are two programs with different dependencies, build steps and deployment targets. Separate packages keep server-only libraries out of the browser bundle and let you deploy, update or replace one half without touching the other.
2. Why split app.js from server.js in an Express project?
app.js builds and exports the app without opening a port, so tests can import it and send requests in memory. server.js handles start-up work, such as connecting to the database and calling listen(), which tests usually want to control themselves.
3. Is it safe to put an API key in a VITE_ environment variable?
No. Vite replaces import.meta.env.VITE_* with the literal value at build time, so it ends up in the JavaScript that every visitor downloads. Secrets must stay on the server, and the client should call your API, which uses the secret on its behalf.
4. Why should every error response have the same JSON shape?
The client can then handle errors in one place, for example one wrapper that reads error.message. It also makes errors predictable for other API users and for tests, and it prevents routes from leaking internal details in their own ad hoc formats.
Key points
- A MEVN repo has
client/(Vue + Vite) andserver/(Express + Mongoose), each with its ownpackage.json. - On the server, one job per file:
config.jsreads env vars,app.jsbuilds the app,server.jsstarts it. - On the client, components call functions in
src/api/; onlyclient.jsknows the base URL. - Server settings:
PORT,MONGODB_URI,CLIENT_ORIGIN,NODE_ENV; client setting:VITE_API_URL.VITE_values are public. - Every path starts with
/api, data is wrapped ({ notes },{ note }), ids areid, and errors are{ error: { code, message } }. - Commit
.env.example, never.env.
Exercise
Kabir has started a MEVN project for his cricket club in Jaipur, but everything is in one folder: index.js (Express routes and mongoose.connect('mongodb://admin:Pass123@...')), Players.vue, card.vue, vite.config.js and one package.json listing both express and vue. Draw the folder tree he should move to, using the NoteNest rules, and list which environment variables he needs on each side.
Show solution
cricket-club/
├── package.json root "dev" script only
├── .gitignore node_modules/, dist/, .env
├── client/
│ ├── package.json vue, vue-router, pinia, vite
│ ├── vite.config.js proxy /api -> http://localhost:3000
│ ├── .env.example VITE_API_URL=/api
│ └── src/
│ ├── api/ client.js, players.js
│ ├── components/ PlayerCard.vue
│ └── views/ PlayersView.vue
└── server/
├── package.json express, mongoose, cors, helmet
├── .env not committed
├── .env.example
└── src/
├── server.js
├── app.js
├── config.js
├── models/Player.js
└── routes/players.jsServer: PORT, MONGODB_URI (the password moves here from the code, and should be changed because it was committed) and CLIENT_ORIGIN. Client: VITE_API_URL only. card.vue becomes PlayerCard.vue (two words), and Players.vue becomes PlayersView.vue because it is a whole page.
Quick Quiz
1. Which file in the NoteNest server is the only one that reads process.env?
Reading settings in one place lets the app check them once and catch typos early.
2. Why does app.js export the app instead of calling listen()?
server.js starts the real server; tests use app directly.
3. What happens to VITE_API_URL during npm run build?
Vite inlines VITE_ variables, so they are public.
4. Which response follows the NoteNest error contract?
Every error uses the same shape with a machine code and a human message.
Learn MEVN Stack with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
