EthicsComputerCourses
Join training +91 90532 10052

Project Structure for MEVN Apps

MEVN Stack · Lesson 3 of 20 Intermediate 11 min read Updated

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.

Text
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.

JavaScript
// 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):

Output
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:

JavaScript
// 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.

JavaScript
// 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
}
JavaScript
// 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.

HTMLOpen in editor
<!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.

NameSideExample valueSecret?
PORTserver3000No
MONGODB_URIservermongodb://127.0.0.1:27017/notenestYes, once it holds a password
CLIENT_ORIGINserverhttp://localhost:5173 (comma-separated for several)No
NODE_ENVserverproduction on the live serverNo
JWT_SECRETserveradded in the login lessonYes
VITE_API_URLclient/apiNever 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 add page or total later without breaking the client.
  • Each note has an id string. The server converts MongoDB's _id before sending, so the client never deals with _id.
  • Status codes carry meaning: 200 OK, 201 created, 204 deleted with no body, 400 bad input, 401 not logged in, 403 not allowed, 404 not found, 500 server fault.
  • Every error, from every route, has the same shape:
JSON
{
  "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

ThingRuleExample
ModulesES modules in both halves ("type": "module")import express from 'express'
Formatting2 spaces, single quotes, no semicolons, lines up to 100 characters (create-vue's Prettier settings)const port = 3000
Vue componentsPascalCase, at least two wordsNoteCard.vue
Route-level componentsPascalCase ending in ViewNotesView.vue
Pinia storesuse + name + Store, file named after the resourceuseNotesStore in stores/notes.js
Mongoose modelsSingular PascalCase, one per fileNote in models/Note.js
Other fileslowercaseroutes/notes.js, api/client.js
JSON fieldscamelCasecreatedAt, pinned
PortsAPI 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 install inside the folder that will use the package. Express inside client/package.json is a sign something went wrong.
  • Calling fetch from inside components. URLs and error handling get copied everywhere. Keep them in src/api/.
  • Reading process.env all over the server. A typo such as process.env.MONGO_URI silently gives undefined. Read everything in config.js.
  • Committing .env. Add .env to .gitignore before 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) and server/ (Express + Mongoose), each with its own package.json.
  • On the server, one job per file: config.js reads env vars, app.js builds the app, server.js starts it.
  • On the client, components call functions in src/api/; only client.js knows 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 are id, 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
Text
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.js

Server: 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?

2. Why does app.js export the app instead of calling listen()?

3. What happens to VITE_API_URL during npm run build?

4. Which response follows the NoteNest error contract?

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