Skip to content

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 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.locals is shared across all requests. Storing a user here would make that user visible to everyone. Use res.locals for request-specific data.

File: app.js

const express = require("express");
const app = express();
// Configuration: Set global application variables
// These are available in ALL views automatically
app.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 Handler
app.get("/", (req, res) => {
// No need to pass 'appTitle' here; it's already in the context
res.render("index");
});

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>
&copy; <%= copyrightYear %> Josh Solomon - Professor Solo - <%= appTitle %>
</p>
<p>License: <%= license %></p>
</footer>

⏭ The Garage Lab

Theory is done. Time to build the machine.