Global Data Context
Passing static configuration data (like a site title or contact email) to every single res.render call violates the “Don’t Repeat Yourself” (DRY) principle. Express provides a mechanism to define global variables that are automatically available to every view in the application, eliminating the need to manually transport them through each route.
The app.locals Object
Section titled “The app.locals Object”The app.locals object is a JavaScript object whose properties are local variables within the application. Once set, these persist throughout the life of the application.
Correct Use Cases:
- Global configuration (Site Name, API keys for client-side scripts).
- Helper functions (Formatters, utility methods).
- Static data (Copyright year, contact info).
Incorrect Use Cases:
- User Sessions: Do not store user-specific data here.
app.localsis shared across all requests. Storing a user here would make that user visible to everyone. Useres.localsfor request-specific data.
Implementation
Section titled “Implementation”File: app.js
const express = require("express");const app = express();
// Configuration: Set global application variables// These are available in ALL views automaticallyapp.locals.appTitle = "Node2Know";app.locals.adminEmail = "ps@professorsolo.com";app.locals.license = "Node2Know Learner License 1.0 (Node2Know-LEARN-1.0)";app.locals.copyrightYear = new Date().getFullYear();
// Route Handlerapp.get("/", (req, res) => { // No need to pass 'appTitle' here; it's already in the context res.render("index");});Usage in Views
Section titled “Usage in Views”In your EJS templates, these properties are accessed as top-level variables. You do not need to prefix them with app.locals.
File: views/partials/footer.ejs
<footer> <p> © <%= copyrightYear %> Josh Solomon - Professor Solo - <%= appTitle %> </p> <p>License: <%= license %></p></footer>