Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restify Middleware - correctly calling next middleware in stack

I am using Restify with Nodejs and I have a question on the correct way of returning control to the next middleware in stack. I hope I am using the correct phrase when I say "next middleware in stack".

Basically, my code looks like this:

//server is the server created using Restify
server.use(function (req, res, next) {
    //if some checks are a success
    return next();
});

Now, what I wish to know is should the code be return next(); or should it be just next(); to pass control to the next in stack?

I checked and both work - that is both pieces of code will successfully pass control and return the data as expected - what I wish to know is if there is a difference between the two and if I need to use one over another.

like image 766
callmekatootie Avatar asked May 14 '13 13:05

callmekatootie


People also ask

What is the next middleware function called?

The next middleware function is commonly denoted by a variable named next. Middleware functions can perform the following tasks: Execute any code. Make changes to the request and the response objects.

How do I create a middleware for nextrequest?

// pages/_middleware.ts import type { NextFetchEvent, NextRequest } from 'next/server' export function middleware(req: NextRequest, ev: NextFetchEvent) { return new Response('Hello, world!') } In this example, we use the standard Web API Response ( MDN ). Middleware is created by using a middleware function that lives inside a _middleware file.

How do you handle the response to a middleware action?

When the response comes back you have two choices: call next or dispatch a new action. The first option, calling next, will take the action you choose and pass it to the next middleware, bypassing all previous ones.

Why is my middleware not ending the request-response cycle?

If the current middleware function does not end the request-response cycle, it must call next () to pass control to the next middleware function. Otherwise, the request will be left hanging. You can load application-level and router-level middleware with an optional mount path.


1 Answers

There's no difference. I took a look at the Restify source, and it doesn't seem to do anything with the return value of a middleware at all.

The reason for using return next() is purely a matter of convenience:

// using this...
if (someCondition) {
  return next();
}
res.send(...);

// instead of...
if (someCondition) {
  next();
} else {
  res.send(...);
};

It might help prevent errors like this:

if (someCondition) 
  next();
res.send(...); // !!! oops! we already called the next middleware *and* we're 
               //     sending a response ourselves!
like image 180
robertklep Avatar answered Oct 07 '22 12:10

robertklep