> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/praveenarya123/sps-backend/llms.txt
> Use this file to discover all available pages before exploring further.

# Environment variables

> Reference for all environment variables required to run the SPS School Backend.

The SPS School Backend uses [dotenv](https://github.com/motdotla/dotenv) to load environment variables from a `.env` file in the project root. This page documents every variable the application reads, how to set secure values, and best practices for different environments.

## How environment variables are loaded

At startup, `server.js` calls `dotenv.config()` before any other application code runs. This populates `process.env` with the values from your `.env` file. If a variable is missing, the relevant feature will fail at runtime — not at startup — so it is important to validate your configuration before deploying.

<Note>
  Variables defined in the shell environment take precedence over values in `.env`. This lets you override settings in CI/CD pipelines and container environments without modifying the file.
</Note>

## Required variables

<ParamField path="body.PORT" type="number" required placeholder="5000">
  The TCP port on which the Express HTTP server listens.

  The server reads this value in `server.js` via `app.listen(process.env.PORT, ...)`. If `PORT` is not set, `process.env.PORT` is `undefined` and Node.js will choose a random available port, which is rarely the intended behavior.

  **Example:** `PORT=5000`

  Common choices are `3000`, `4000`, `5000`, or `8080` for local development. In hosted environments (Heroku, Railway, Render), the platform injects `PORT` automatically — do not hard-code it.
</ParamField>

<ParamField path="body.MONGODB_URI" type="string" required placeholder="mongodb://localhost:27017/sps-school">
  The MongoDB connection string passed to Mongoose in `config/db.js`.

  Mongoose uses this URI to establish and maintain the database connection. The URI encodes the host, port, authentication credentials, and target database name.

  **Local example:**

  ```
  MONGODB_URI=mongodb://localhost:27017/sps-school
  ```

  **MongoDB Atlas example:**

  ```
  MONGODB_URI=mongodb+srv://myuser:mypassword@cluster0.abcde.mongodb.net/sps-school?retryWrites=true&w=majority
  ```

  <Warning>
    Atlas connection strings contain your database username and password. Never commit a `.env` file containing a real `MONGODB_URI` to version control.
  </Warning>
</ParamField>

<ParamField path="body.JWT_SECRET" type="string" required placeholder="a-long-random-secret-string">
  The secret key used to sign and verify JSON Web Tokens in `authController.js` and `authMiddleware.js`.

  When a user logs in, the server signs a JWT with this secret. On subsequent authenticated requests, the middleware verifies the token's signature using the same secret. If the secret changes, all previously issued tokens become invalid and users must log in again.

  **Example:**

  ```
  JWT_SECRET=3f8a2c1d9e6b4a7f0c5d2e8b1a4f7c9d3e6b2a8f1c4d7e0b3a6f9c2d5e8b1a4
  ```

  See [generating a strong JWT secret](#generating-a-strong-jwt-secret) below for instructions.

  <Warning>
    Use a different `JWT_SECRET` in every environment (development, staging, production). A secret that leaks from a development machine must not be able to forge tokens in production.
  </Warning>
</ParamField>

## Generating a strong JWT secret

A JWT secret should be at least 32 bytes of cryptographically random data. Use one of the following methods to generate one:

<Tabs>
  <Tab title="openssl">
    ```bash theme={null}
    openssl rand -hex 64
    ```

    This outputs 64 hex characters (32 bytes of entropy). Copy the output directly into your `.env` file.
  </Tab>

  <Tab title="Node.js crypto">
    ```bash theme={null}
    node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
    ```

    Run this from your terminal (Node.js must be installed). The output is 128 hex characters (64 bytes of entropy).
  </Tab>

  <Tab title="Node.js REPL">
    ```javascript theme={null}
    // Open the Node.js REPL with: node
    require('crypto').randomBytes(64).toString('base64')
    // Copy the printed string into JWT_SECRET
    ```

    Base64 encoding produces a slightly shorter string for the same entropy.
  </Tab>
</Tabs>

<Tip>
  Prefer base64url or hex over dictionary words or passphrases. JWT secrets are never shown to users, so memorability is not a requirement — only entropy matters.
</Tip>

## Complete .env template

Create a `.env` file in the project root with the following structure. Replace all placeholder values before starting the server.

```bash .env theme={null}
# -----------------------------------------------
# SPS School Backend — environment configuration
# -----------------------------------------------
# Do NOT commit this file to version control.
# Add .env to your .gitignore file.

# Server
PORT=5000

# Database
# Local MongoDB:
MONGODB_URI=mongodb://localhost:27017/sps-school
# MongoDB Atlas (uncomment and fill in your credentials):
# MONGODB_URI=mongodb+srv://<username>:<password>@cluster0.abcde.mongodb.net/sps-school?retryWrites=true&w=majority

# Authentication
# Generate with: openssl rand -hex 64
JWT_SECRET=replace-this-with-a-long-random-secret
```

## Keeping .env out of version control

<Warning>
  Committing a `.env` file with real credentials to a public or shared repository is a common source of credential leaks. Always add `.env` to `.gitignore`.
</Warning>

Ensure your `.gitignore` includes:

```text .gitignore theme={null}
# Environment variables
.env
.env.local
.env.*.local
```

If you accidentally committed a `.env` file in the past, rotate every secret it contained (generate a new `JWT_SECRET`, rotate your MongoDB credentials) and remove it from the git history using `git filter-repo` or `BFG Repo Cleaner`.

Commit a `.env.example` file instead — a copy of the template with all values replaced by safe placeholders:

```bash .env.example theme={null}
PORT=5000
MONGODB_URI=mongodb://localhost:27017/sps-school
JWT_SECRET=replace-with-random-secret
```

This file is safe to commit and gives new developers a clear picture of required configuration without exposing real secrets.

## Environment-specific configuration

<AccordionGroup>
  <Accordion title="Development">
    * Use a local MongoDB instance to keep development data isolated from staging and production.
    * Any value works for `JWT_SECRET` locally, but use a randomly generated one so you catch token-related issues early.
    * Set `PORT` to whatever is free on your machine (`5000` is the default).

    ```bash theme={null}
    PORT=5000
    MONGODB_URI=mongodb://localhost:27017/sps-school-dev
    JWT_SECRET=dev-only-secret-do-not-reuse
    ```
  </Accordion>

  <Accordion title="Staging">
    * Use a separate MongoDB database or Atlas cluster from production.
    * Generate a unique `JWT_SECRET` — do not share it with the production secret.
    * If your staging environment is publicly accessible, treat its credentials with the same care as production.

    ```bash theme={null}
    PORT=5000
    MONGODB_URI=mongodb+srv://staging-user:password@cluster0.abcde.mongodb.net/sps-school-staging
    JWT_SECRET=<randomly-generated-staging-secret>
    ```
  </Accordion>

  <Accordion title="Production">
    * Inject environment variables through your hosting platform's secrets manager rather than a `.env` file on disk. Most platforms (Heroku, Railway, Render, AWS ECS, Kubernetes) support this natively.
    * Enable MongoDB Atlas IP allowlisting and restrict access to your server's IP range.
    * Rotate `JWT_SECRET` periodically. Note that rotation invalidates all active sessions.
    * Set `PORT` only if the platform does not inject it automatically.

    <Warning>
      Never store production secrets in a `.env` file inside a Docker image, a git repository, or a shared file system.
    </Warning>
  </Accordion>
</AccordionGroup>

## Variable summary

| Variable      | Required | Default | Description               |
| ------------- | -------- | ------- | ------------------------- |
| `PORT`        | Yes      | —       | HTTP server listen port   |
| `MONGODB_URI` | Yes      | —       | MongoDB connection string |
| `JWT_SECRET`  | Yes      | —       | Secret for signing JWTs   |
