Home

Issue: 2994

The middleware to prevent access to SSR resource will fail

[issue link]

I don’t know is it necessary to prevent access to SSR resource.
But I saw it actually has a middleware in /lib/core/renderer.js to do this.

And it would fail if we send path with url encoded.
For example:

GET /_nuxt/server-bundle%2Ejson HTTP/1.1
Host: nuxtjs.org

The first middleware will directly check that it’s not in req.url for every filename in resourceMap.
https://github.com/nuxt/nuxt.js/blob/v1.4.0/lib/core/renderer.js#L221

    // Common URL checks
    this.useMiddleware((req, res, next) => {
      // Prevent access to SSR resources
      if (ssrResourceRegex.test(req.url)) {
        res.statusCode = 404
        return res.end()
      }
      next()
    })

Then use serve-static package to serve .nuxt/dist/ files.
https://github.com/nuxt/nuxt.js/blob/v1.4.0/lib/core/renderer.js#L259

    // Serve .nuxt/dist/ files only for production
    // For dev they will be served with devMiddleware
    if (!this.options.dev) {
      const distDir = resolve(this.options.buildDir, 'dist')
      this.useMiddleware({
        path: this.publicPath,
        handler: serveStatic(distDir, {
          index: false, // Don't serve index.html template
          maxAge: '1y' // 1 year in production
        })
      })
    }

In serve-static package, it will call send packege to serve the file,
server-static directly calls it with send(req, parseUrl(req).pathname, opt).
https://github.com/expressjs/serve-static/blob/v1.13.2/index.js#L95

    var path = parseUrl(req).pathname;

    // create send stream
    var stream = send(req, path, opts)

But before send create the file stream, it would do a url decode on req.path.
https://github.com/pillarjs/send/blob/0.16.2/index.js#L517

  // decode the path
  var path = decode(this.path)

So server-bundle%2Ejson will be decoded to server-bundle.json, and the first middleware won’t match it.

This question is available on Nuxt.js community (#c2595)