Express.js – app.locals Property


The app.locals object defines the properties that are local variables inside an application. Once the value of app.locals property is set, it persists throughout the life of the application. The res.locals property is valid only for the lifetime of the request.

Syntax

app.locals

Example 1

Create a file "appLocals.js" and copy the following code snippet. After creating the file, use the command "node appLocals.js" to run this code.

// app.locals code Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Setting the below email throught out the application
app.locals.email = 'hi@tutorialspoint.com'

console.log("Email Configured is: ", app.locals.email);

Output

C:\home
ode>> node appLocals.js Email Configured is: hi@tutorialspoint.com

Example 2

Let’s take a look at one more example.

// app.locals code Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Setting the multiple variables throughout the application
app.locals.domain = 'www.tutorialspoint.com'
app.locals.age = '30'
app.locals.company = 'Tutorials Point Ltd'

console.log(app.locals);

Output

C:\home
ode>> node appLocals.js [Object: null prototype] {    settings:       { 'x-powered-by': true,          etag: 'weak',         'etag fn': [Function: generateETag],          env: 'development',         'query parser': 'extended',         'query parser fn': [Function: parseExtendedQueryString],         'subdomain offset': 2,         'trust proxy': false,         'trust proxy fn': [Function: trustNone],          view: [Function: View],          views: '/home/mayankaggarwal/mysql-test/views',         'jsonp callback name': 'callback' },       domain: 'www.tutorialspoint.com',       age: '30',       company: 'Tutorials Point Ltd' }

Updated on: 30-Sep-2021

815 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements