nestjs / serve-static

Serve static websites (SPA's) using Nest framework (node.js) šŸ„¦

Home Page:https://nestjs.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Global guards aren't applied for content served by this module

TimonLukas opened this issue Ā· comments

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

A globally registered guard isn't called before content is served by this module.

Expected behavior

Since global guards are supposed to apply to every endpoint, I'd expect them to also apply to content served by this module (at least as long as the global guard was registered by a module before the ServeStaticModule was registered), or at least for the module to have a configuration option to allow this.

Minimal reproduction of the problem with instructions

  1. Create a new Nest application, and register a global guard
  2. Add the ServeStatic module, and configure it to serve some static files.
  3. Try to access the static files - the guard won't be called.

What is the motivation / use case for changing the behavior?

I'm using Nest to write internal tooling which will be publicly accessible. I want to make sure no information is possibly leaked, so users will have to authenticate using our company-internal SSO. To implement this I created a strategy and guard and added them to the application using passport. Since the guard isn't applied to content served by this module I have two choices:

  1. Rewrite the module manually and integrate the guard into those routes (the frontend is a Vue SPA for which I do need the history fallback, making this option kinda annoying)
  2. Not use guards at all and implement the authentication completely through middleware

Right now I'm leaning more towards the latter option, but this would mean circumventing Nest's application structure, which I'd like to avoid if possible.

Environment


Nest version: 7.2.0

This package simply wraps the express.static() middleware. Guards are not executed for middleware functions (see this chapter for more details on Request Lifecycle https://docs.nestjs.com/faq/request-lifecycle). I would recommend not using this package but rather implement "files serve" logic inside your controllers.

I'm aware that the module currently is a simple wrapper around the express middleware. Still, is there no possible way to add a feature like this? My big selling point for Nest is that a large amount of useful tools which work well together is automatically provided. This seems to be an undocumented exception, and although I can implement what you described, I'm reasonably sure that my implementation will have more unforeseen edge cases, as will any other developers'.