Skip to main content

Overview

The Portal Self-Service Backend requires several environment variables to configure database connections, Azure AD authentication, server settings, and CORS policies.

Environment Variables

Server Configuration

Server Port

PORT=3000
The port on which the Express server will listen. Defaults to 3000 if not specified.

Database Configuration

All database variables are required for the application to start. See the Database Setup guide for detailed configuration.
DB_USER=your_database_user
DB_PASSWORD=your_database_password
DB_SERVER=localhost
DB_DATABASE=PortalSelfService
DB_PORT=1433
VariableDescriptionRequired
DB_USERDatabase authentication username✅ Yes
DB_PASSWORDDatabase authentication password✅ Yes
DB_SERVERDatabase server hostname or IP address✅ Yes
DB_DATABASETarget database name✅ Yes
DB_PORTSQL Server port (typically 1433)✅ Yes

Azure AD Authentication

Azure AD configuration is critical for API security. All protected endpoints require valid JWT tokens issued by Microsoft Entra ID (formerly Azure AD).
The application uses Azure AD for authentication via JWT bearer tokens:
AZURE_ISSUER_BASE_URL=https://login.microsoftonline.com/{tenant-id}/v2.0
AZURE_AUDIENCE=api://your-api-application-id
VariableDescriptionExample
AZURE_ISSUER_BASE_URLAzure AD token issuer URL including tenant IDhttps://login.microsoftonline.com/{tenant-id}/v2.0
AZURE_AUDIENCEApplication ID URI of your backend API registered in Azureapi://your-backend-api-id

How It’s Used

Authentication Middleware (src/middleware/authMiddleware.js):
import { auth } from 'express-oauth2-jwt-bearer';

const checkJwtBase = auth({
    issuerBaseURL: process.env.AZURE_ISSUER_BASE_URL, 
    audience: process.env.AZURE_AUDIENCE,
});
WebSocket Authentication (src/config/socket.js):
const client = jwksClient({
    jwksUri: `${process.env.AZURE_ISSUER_BASE_URL}/discovery/v2.0/keys`
});

jwt.verify(token, getKey, {
    audience: process.env.AZURE_AUDIENCE,
    issuer: process.env.AZURE_ISSUER_BASE_URL
}, async (err, decoded) => {
    // Validation logic
});
1

Get Your Tenant ID

  1. Go to Azure Portal → Azure Active Directory
  2. Copy the Directory (tenant) ID
  3. Use format: https://login.microsoftonline.com/{tenant-id}/v2.0
2

Get Your API Application ID

  1. Go to Azure Portal → App Registrations
  2. Select your backend API registration
  3. Copy the Application ID URI (format: api://your-app-id)
3

Configure Environment Variable

Set both AZURE_ISSUER_BASE_URL and AZURE_AUDIENCE in your .env file

Frontend Configuration

Frontend URL

FRONTEND_URL=http://localhost:5173
The URL of your frontend application. Used for:
  • CORS configuration (API requests)
  • WebSocket CORS (Socket.io connections)
The default CORS origin in src/app.js is http://localhost:5173. Update both the FRONTEND_URL variable and the hardcoded corsOptions for consistency.
Current CORS configuration in src/app.js:
const corsOptions = {
    origin: 'http://localhost:5173', // Should match FRONTEND_URL
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    credentials: true,
    optionsSuccessStatus: 204
};

File Upload Configuration

Base URL

BASE_URL=http://localhost:3000
The base URL of your backend API. Used for generating file upload URLs.
Used in src/controllers/uploadController.js:
const baseUrl = process.env.BASE_URL || 'http://localhost:3000';
const fileUrl = `${baseUrl}/uploads/${filename}`;

Complete .env Template

Create a .env file in the root of your project with the following structure:
# Server Configuration
PORT=3000

# Database Configuration
DB_USER=sa
DB_PASSWORD=YourLocal@Passw0rd
DB_SERVER=localhost
DB_DATABASE=PortalSelfService
DB_PORT=1433

# Azure AD Authentication
AZURE_ISSUER_BASE_URL=https://login.microsoftonline.com/your-tenant-id/v2.0
AZURE_AUDIENCE=api://your-backend-api-id

# Frontend Configuration
FRONTEND_URL=http://localhost:5173

# File Upload
BASE_URL=http://localhost:3000

Environment Variable Reference Table

VariableTypeRequiredDefaultDescription
PORTnumberNo3000HTTP server port
DB_USERstringYes-Database username
DB_PASSWORDstringYes-Database password
DB_SERVERstringYes-Database server hostname
DB_DATABASEstringYes-Database name
DB_PORTnumberYes-Database port (typically 1433)
AZURE_ISSUER_BASE_URLstringYes-Azure AD issuer URL with tenant ID
AZURE_AUDIENCEstringYes-API application ID URI
FRONTEND_URLstringNohttp://localhost:5173Frontend application URL for CORS
BASE_URLstringNohttp://localhost:3000Backend base URL for file uploads

Security Best Practices

Never Commit .env

Add .env to your .gitignore file to prevent exposing secrets in version control.
.gitignore
.env
.env.local
.env.*.local

Use Strong Passwords

Database passwords should be:
  • At least 12 characters
  • Include uppercase, lowercase, numbers, and symbols
  • Different from development passwords

Rotate Credentials

Periodically rotate:
  • Database passwords
  • Azure AD client secrets
  • Any API keys

Use Azure Key Vault

For production deployments, consider using Azure Key Vault or similar secret management services instead of plain .env files.

Validation

To verify your environment configuration:
1

Create .env File

Copy the template above and fill in your values.
2

Install Dependencies

npm install
3

Start the Application

npm start
4

Check Console Output

Look for successful startup messages:
Conexión a SQL Server establecida.
Servidor escuchando en http://localhost:3000
5

Test Health Endpoint

curl http://localhost:3000/health
If the database connection fails, the application will exit with code 1. Verify all DB_* environment variables are correct.

Troubleshooting

Missing Environment Variables

If you see errors about undefined environment variables:
  1. Ensure .env file exists in the project root
  2. Verify dotenv is loaded in server.js:
    import 'dotenv/config';
    
  3. Check that variable names match exactly (case-sensitive)

Azure AD Authentication Errors

Invalid Token

Symptoms: 401 Unauthorized or “Token inválido” errorsSolutions:
  • Verify AZURE_ISSUER_BASE_URL includes your correct tenant ID
  • Ensure AZURE_AUDIENCE matches the Application ID URI in Azure
  • Check that the frontend is requesting tokens with the correct scope
  • Verify token hasn’t expired

CORS Errors

CORS Policy Blocked

Symptoms: Browser console shows CORS policy errorsSolutions:
  • Verify FRONTEND_URL matches your frontend application URL
  • Update corsOptions.origin in src/app.js to use process.env.FRONTEND_URL
  • Ensure frontend makes requests with credentials: 'include' if using cookies

Next Steps

Database Setup

Configure your MSSQL database connection

Deployment

Deploy your application to production

Build docs developers (and LLMs) love