464

In the docs for the NodeJS express module, the example code has app.use(...).

What is the use function and where is it defined?

8
  • 7
    possible duplicate: stackoverflow.com/questions/7337572/… Commented Jul 4, 2012 at 2:30
  • 82
    the documentation is a bit cryptic for a beginner Commented Apr 27, 2018 at 4:43
  • 12
    Possible duplicate above is referencing each other Commented Sep 2, 2018 at 7:10
  • 7
    The documentation is completely unclear
    – Trect
    Commented Dec 29, 2019 at 22:01
  • 5
    @KansaiRobot I'm a beginner and its nice to see someone actually thinks its not straightforward! Commented May 6, 2020 at 8:06

33 Answers 33

479

The app object is instantiated on creation of the Express server. It has a middleware stack that can be customized in app.configure()(this is now deprecated in version 4.x).

To setup your middleware, you can invoke app.use(<specific_middleware_layer_here>) for every middleware layer that you want to add (it can be generic to all paths, or triggered only on specific path(s) your server handles), and it will add onto your Express middleware stack. Middleware layers can be added one by one in multiple invocations of use, or even all at once in series with one invocation. See use documentation for more details.

To give an example for conceptual understanding of Express Middleware, here is what my app middleware stack (app.stack) looks like when logging my app object to the console as JSON:

stack: 
   [ { route: '', handle: [Function] },
     { route: '', handle: [Function: static] },
     { route: '', handle: [Function: bodyParser] },
     { route: '', handle: [Function: cookieParser] },
     { route: '', handle: [Function: session] },
     { route: '', handle: [Function: methodOverride] },
     { route: '', handle: [Function] },
     { route: '', handle: [Function] } ]

As you might be able to deduce, I called app.use(express.bodyParser()), app.use(express.cookieParser()), etc, which added these express middleware 'layers' to the middleware stack. Notice that the routes are blank, meaning that when I added those middleware layers I specified that they be triggered on any route. If I added a custom middleware layer that only triggered on the path /user/:id that would be reflected as a string in the route field of that middleware layer object in the stack printout above.

Each layer is essentially adding a function that specifically handles something to your flow through the middleware.

E.g. by adding bodyParser, you're ensuring your server handles incoming requests through the express middleware. So, now parsing the body of incoming requests is part of the procedure that your middleware takes when handling incoming requests -- all because you called app.use(bodyParser).

9
  • 162
    thank you. would it be so difficult for the express folks to explain this in their API docs?
    – ericsoco
    Commented Jun 25, 2013 at 21:52
  • 6
    So you're saying that when a request is received the data is passed through those parsers before hitting the actual service. So for example: Valid Request->Authentication->ProcessesRequest->ServResponse USE would control those steps in a specific order and not execute them parallel?
    – Adam Hess
    Commented Oct 10, 2013 at 19:10
  • 12
    When is the function that is sent to app.use called? After creating the express server or for every request? Commented Nov 21, 2013 at 18:25
  • 3
    @Jon In Express there is only middlewares. Express.js does not implement anything else apart from a middleware (plugin) architecture. The middleware can be anything. A route is just a special type of middleware (Note that app.get, app.post etc are just convenience helpers around app.use. You can in fact load middlewares using app.get instead of app.use if you don't want the middleware to handle post requests)
    – slebetman
    Commented Sep 17, 2019 at 6:11
  • 9
    @KevinC. No, it is not dependency injection. It is a plugin architecture. Generally this kind of architecture is called a filter system / filter pipeline / pipe and filter. In Express the pipe is the next() callback each middleware is expected to call to pass processing to the next function in the pipeline. The routing system (the first argument to app.use()) allows the pipeline to branch depending on URL
    – slebetman
    Commented Sep 17, 2019 at 6:18
147

Each app.use(middleware) is called every time a request is sent to the server.

2
  • 44
    Your single sentence answer is instantly understandable and more helpful than the other multi-paragraph explanations. Commented Nov 30, 2019 at 22:17
  • 2
    Only thing that it should be invoked before app.get. Else it never gets called.
    – Atul
    Commented Aug 6, 2022 at 8:33
57

use is a method to configure the middleware used by the routes of the Express HTTP server object. The method is defined as part of Connect that Express is based upon.

Update Starting with version 4.x, Express no longer depends on Connect.

The middleware functions that were previously included with Express are now in separate modules; see the list of middleware functions.

4
  • 3
    And the online docs are here: senchalabs.org/connect/proto.html#app.use Commented Jul 4, 2012 at 2:47
  • Would it be efficient if a Node middleware instantiates objects? Would this mean that on every request, that middleware instantiates new objects? Do the old objects get discarded? For example app.use(function(){ var object = new SomeConstructor; next(); }) Commented Mar 6, 2014 at 14:01
  • 1
    @CMCDragonkai It's fine to instantiate objects on every request. They'll get garbage collected so long as you're not storing references to the objects outside the scope of your request handler. Commented Dec 16, 2015 at 2:45
  • 1
    @AlexanderBird thx for the links (the 1st one is broken now though). For the record, just the begining of the doc in the 2nd link says "Utilize the given middleware handle to the given route, defaulting to /. This "route" is the mount-point for the middleware, when given a value other than / the middleware is only effective when that segment is present in the request's pathname. For example if we were to mount a function at /admin, it would be invoked on /admin, and /admin/settings, however it would not be invoked for /, or /posts". Simple :)
    – Adriano
    Commented Dec 17, 2015 at 4:31
34

app.use() acts as a middleware in express apps. Unlike app.get() and app.post() or so, you actually can use app.use() without specifying the request URL. In such a case what it does is, it gets executed every time no matter what URL's been hit.

0
19

app.use() used to Mounts the middleware function or mount to a specified path,the middleware function is executed when the base path matches.

For example: if you are using app.use() in indexRouter.js , like this:

//indexRouter.js

var adsRouter = require('./adsRouter.js');

module.exports = function(app) {
    app.use('/ads', adsRouter);
}

In the above code app.use() mount the path on '/ads' to adsRouter.js.

Now in adsRouter.js

// adsRouter.js

var router = require('express').Router();
var controllerIndex = require('../controller/index');
router.post('/show', controllerIndex.ads.showAd);
module.exports = router;

in adsRouter.js, the path will be like this for ads- '/ads/show', and then it will work according to controllerIndex.ads.showAd().

app.use([path],callback,[callback]) : we can add a callback on the same.

app.use('/test', function(req, res, next) {

  // write your callback code here.

    });
1
  • I'd use "map" in place of "mount", easier to understand.
    – Jeb50
    Commented Jan 27, 2019 at 0:59
14

app.use() handles all the middleware functions.
What is middleware?
Middlewares are the functions which work like a door between two all the routes.

For instance:

app.use((req, res, next) => {
    console.log("middleware ran");
    next();
});

app.get("/", (req, res) => {
    console.log("Home route");
});

When you visit / route in your console the two message will be printed. The first message will be from middleware function. If there is no next() function passed then only middleware function runs and other routes are blocked.

1
  • 2
    From Review: Do we really need yet another answer in this thread? Commented Sep 3, 2020 at 11:48
13
app.use(function middleware1(req, res, next){
   // middleware1 logic
}, function middleware2(req, res, next){
   // middleware2 logic
}, ... middlewareN);

app.use is a way to register middleware or chain of middlewares (or multiple middlewares) before executing any end route logic or intermediary route logic depending upon order of middleware registration sequence.

Middleware: forms chain of functions/middleware-functions with 3 parameters req, res, and next. next is callback which refer to next middleware-function in chain and in case of last middleware-function of chain next points to first-middleware-function of next registered middlerare-chain.

0
9

app.use() works like that:

  1. Request event trigered on node http server instance.
  2. express does some of its inner manipulation with req object.
  3. This is when express starts doing things you specified with app.use

which very simple.

And only then express will do the rest of the stuff like routing.

7

The .use() method in express is a *middleware handler. An Express application is essentially a series of middleware function calls.

An Express application can use 5 different types of middleware, of which these two are majorly used:

  1. Application-level middleware
  2. Router-level middleware

App.use() is used to bind *application-level middleware to an instance of the app object which is instantiated on the creation of the Express server (router.use() for router-level middleware).

Syntax : app.use(path, middleware function/s)

Here, the path is optional. When no path is specified the function gets executed every time the app receives a request, irrespective of which URL has been hit.

*Example:
Auth middleware - In a To-Do app, once an already created user logs in, he is provided with a JWT token, which must be verified every time the user makes a GET, PUT, PATCH, POST or DELETE request.

app.use("/api/*", verifyToken(req, res, next): void {
const jwt: string = req.headers['x-token-header'];
if (!jwt) {
  res.status(403).send({ message: 'No token provided!' });
} else {
  jsonwebtoken.verify(jwt, config.get('secretString'), (err) => {
    if (err) {
      res.status(403).send(err);
    } else {
      next();
    }
  });
});

Here, the path /api has been added to differentiate from requests that do not need a JWT authentication such as sign up and log in (since we don't want the middleware to be executed when there's no need for authentication).

*Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

Syntax of a middleware: function(req, res, next)

3
  • This explanations is more precisely answered the question.
    – H.C.Chen
    Commented May 10, 2021 at 2:41
  • so for signin or singup page, we cannot use route path "/api/login" "/api/signup" ?
    – Akin Zeman
    Commented Jul 24, 2021 at 21:48
  • @AkinZeman, yes in this particular scenario, paths that start with /api all need a JWT token, whereas the login & signup paths don't need the token. Commented Apr 21, 2022 at 8:52
4

In express if we import express from "express" and use app = express(); then app having all functionality of express

if we use app.use()

with any module/middleware function to use in whole express project

4

app.use is woks as middleware for app request. syntax

app.use('pass request format',function which contain request response onject)

example

app.use('/',funtion(req,res){
 console.log(all request pass through it);
// here u can check your authentication and other activities.
})

also you can use it in case of routing your request.

app.use('/', roting_object);
3

app.use is a function requires middleware. For example:

 app.use('/user/:id', function (req, res, next) {
       console.log('Request Type:', req.method);
        next();
     });

This example shows the middleware function installed in the /user/:id path. This function is executed for any type of HTTP request in the /user/:id path.

It is similar to the REST Web Server, just use different /xx to represent different actions.

1
  • thanks for the answer, but since someone else already said all that information I won't upvote this one. I don't think I need every explanation of what express use can do; I just needed to know that's what it was (and any context knowledge to know how to go research more myself). Commented Oct 29, 2018 at 1:50
3

app.use() is a method that allows us to register a middleware.

The middleware method is like an interceptor in java, this method always executes for all requests.

Purpose and use of middleware:-

  1. To check if the session expired or not
  2. for user authentication and authorization
  3. check for cookie (expiry date)
  4. parse data before the response
1
  • Middleware is the function passed into app.use().
    – nCardot
    Commented Feb 6, 2020 at 5:46
2

Middleware is a general term for software that serves to "glue together" so app.use is a method to configure the middleware, for example: to parse and handle the body of request: app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); there are many middlewares you can use in your express application just read the doc : http://expressjs.com/en/guide/using-middleware.html

2

app.use applies the specified middleware to the main app middleware stack. When attaching middleware to the main app stack, the order of attachment matters; if you attach middleware A before middleware B, middleware A will always execute first. You can specify a path for which a particular middleware is applicable. In the below example, “hello world” will always be logged before “happy holidays.”

const express = require('express')
const app = express()

app.use(function(req, res, next) {
  console.log('hello world')
  next()
})

app.use(function(req, res, next) {
  console.log('happy holidays')
  next()
})
2

It enables you to use any middleware (read more) like body_parser,CORS etc. Middleware can make changes to request and response objects. It can also execute a piece of code.

1
  • Thanks for the answer, but I believe all that information is already captured in other answers Commented Dec 5, 2018 at 19:37
2

You can also create your own middleware function like

app.use( function(req, res, next) {
  // your code 
  next();
})

It contains three parameters req, res, next
You can also use it for authentication and validation of input params to keep your controller clean.

next() is used for go to next middleware or route.
You can send the response from middleware

2

app.use is Application level middleware

Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.

you can use to check all requests, for example, you want to check token/access token you need to write a middleware by using app.use to check the token in the request.

This example shows a middleware function with no mount path. The function is executed every time the app receives a request.

var app = express()

app.use(function (req, res, next) {
  console.log('Time:', Date.now())
  next()
})

reference from https://expressjs.com/en/guide/using-middleware.html

1
  • 1
    app.use() is not middleware. Middleware is the function passed into app.use()
    – nCardot
    Commented Feb 6, 2020 at 5:47
2

app.use(path, middleware) is used to call middleware function that needs to be called before the route is hit for the corresponding path. Multiple middleware functions can be invoked via an app.use.

app.use(‘/fetch’, enforceAuthentication) -> enforceAuthentication middleware fn will be called when a request starting with ‘/fetch’ is received. It can be /fetch/users, /fetch/ids/{id}, etc

Some middleware functions might have to be called irrespective of the request. For such cases, a path is not specified, and since the the path defaults to / and every request starts with /, this middleware function will be called for all requests.

app.use(() => { // Initialize a common service })

next() fn needs to be called within each middleware function when multiple middleware functions are passed to app.use, else the next middleware function won’t be called.

reference : http://expressjs.com/en/api.html#app.use

Note: The documentation says we can bypass middleware functions following the current one by calling next('route') within the current middleware function, but this technique didn't work for me within app.use but did work with app.METHOD like below. So, fn1 and fn2 were called but not fn3.

app.get('/fetch', function fn1(req, res, next)  {
    console.log("First middleware function called"); 
        next();
    }, 
    function fn2(req, res, next) {
        console.log("Second middleware function called"); 
        next("route");
    }, 
    function fn3(req, res, next) {
        console.log("Third middleware function will not be called"); 
        next();
    })
2

In simple words app.use() is a function that takes another function (callback) as a parameter and runs every time, when the request is sent to the express app/server.

The function passed inside app.use is also called middleware, middleware is just a fancy name for a function that exists in express app and has three parameters request, response and next. You can read more about middleware.

Middleware are called between request and response cycle. If you want a middleware to be applied on all the routes then you can use app.use() or do some validation, error checking and other things.

2

app.use(req, res, next) is an API that allows us to add one or more middlewares to the request pipeline of express. A middleware is a function that has a defined signature, and through that, you can modify or end the request, returning a response according to a condition that you program. For example, I can call res.end() and finish the request to the client. Middlewares are executed in the order they're added. I can simply decorate the req object, adding or removing properties, for example, authenticating an user and setting req.user = 'any user of database', and calling next(), the next middleware will begin its execution, receiving the same instance of req, res, next.

2

app.use() acts as a middleware, where using it you can declare route specific middlewares

// in server.js
import Users from '../routes/Users.js'
import Posts from '../routes/Posts.js'
...
app.use('/users', Users)
app.use('/posts', Posts)
...

along with that you may use it to declare global middlewares

app.use(cors())
app.use(express.json())
1

Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.

1

In short app.use() supports all type of requests [eg:get,post,...] so its mostly used to setup middelware. or can be used for when the routes and functions seperated

example:

app.use("/test",functionName)

and functionName is located in different file

1
  • Thanks for the answer, but I believe all that information is already captured in other answers. Commented Nov 29, 2018 at 20:21
1

app.use
is created by express(nodejs middleware framework )
app.use is use to execute any specific query at intilization process
server.js(node)
var app = require('express');
app.use(bodyparser.json())
so the basically app.use function called every time when server up

1

You can use app.use('/apis/test', () => {...}) for writing middleware for your api, to handle one or some action (authentication, validation data, validation tokens, etc) before it can go any further or response with specific status code when the condition that you gave was not qualified.

Example:

var express = require('express')
var app = express()

app.use(function (req, res, next) {
  // Your code to handle data here
  next()
})

More detail is, this part actually an anonymous function for you to write the logic on runtime

function (req, res, next) {
   // Your code to handle data here
   next()
}

You can split it into another function from another file and using module.export to use

next() here for the logic that if you handle everything is fine then you can use then for the program to continue the logic that its used to.

1

The app.use() function is used to mount the specified middleware function(s) at the path which is being specified. It is mostly used to set up middleware for your application.
Syntax
app.use(path, callback)
Parameters:

  1. path: It is the path for which the middleware function is being called. It can be a string representing a path or path pattern or regular expression pattern to match the paths.
  2. callback: It is a middleware function or a series/array of middleware functions.
1

app.use() will be called for every request: GET, POST, PUT, PATCH, DELETE

1

Let's say we have a set of routes that our site can handle

app.get('/1/', function(req, res) {
    res.send('page1');
});

app.get('/2/', function(req, res) {
    res.send('page2');
});

Obviously, if an address is requested that we do not process, then a 404 error should be returned. Express, however, does not do this by default. But it's easy to implement.

The special method app.use will help us with this. It allows you to intercept all raw addresses

Let's use this method to return a 404 error

app.use(function(req, res) {
    res.status(404).send('not found');
});

Now let's place our construction after all app.get

app.get('/1/', function(req, res) {
    res.send('page1');
});

app.get('/2/', function(req, res) {
    res.send('page2');
});

app.use(function(req, res) {
    res.status(404).send('not found');
});
1

The app. use() function is used to mount the specified middleware function(s) at the path which is being specified. It is mostly used to set up middleware for your application.

Not the answer you're looking for? Browse other questions tagged or ask your own question.