kartikk221 / hyper-express

High performance Node.js webserver with a simple-to-use API powered by uWebsockets.js under the hood.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Route handlers are not registered correctly

hanc2006 opened this issue · comments

Hi,

I'm trying to create a simple project with this library, but I have some trouble. I think the routes registration are not handled correctly. The handler is called twice every time.

Let's take this simple example. By registering a middleware or a route, the behavior will be what I described above .

import HyperExpress, { MiddlewareNext, Request, Response } from 'hyper-express';

const webserver = new HyperExpress.Server();

const specificMiddleware1 = (request: Request, response: Response, next: MiddlewareNext) => {
 // This is called twice
  console.log('route specific middleware 1 ran!');
  next();
};

const specific_middleware2 = (request: Request, response: Response, next: MiddlewareNext) => {
  // This is called twice
  console.log('route specific middleware 2 ran!');
  next();
};


// webserver.use(specificMiddleware1);
// webserver.use(specific_middleware2);

webserver.get(
  '/',
  //   {
  //     middlewares: [specificMiddleware1, specific_middleware2],
  //   },
  (request: Request, response: Response) => {
    // This is called twice
    console.log('called');
    response.send('Hello World');
  },
);

webserver.listen(3000);

`

Hello, It seems that you misunderstood how the middleware binding works. After trying your snippet above, I am seeing the following behavior:

  • The route handler aka. called log only gets logged once no matter what.
  • The specific middleware 1 and 2 only run twice If you do webserver.use() AND also specify a middlewares property on the route options. By doing this, you are effectively binding the same middleware twice.

The webserver.use() call is binding a global middleware meaning the middleware being assigned will run on ALL routes on the server.

On the contrary, the middlewares object specified on the route options will only run those middlewares on that route's requests.

The route handler should never be called twice. You can validate that the route handler never gets called by using code like below:

webserver.get('/', (request, response) => {
   // The below code will only log the warning if the same request is called twice on the handler
   if (request.called_already) console.warn('Detected the same route handler being called twice with the same request');
   request.called_already = true;
});

With that said, this does not seem to be a bug in hyper-express but rather incorrect usage. Hope that helps!