Skip to content

Reusing Error Page with Custom Server (Express) #2866

@adrianmcli

Description

@adrianmcli
  • I have searched the issues of this repository for the phrase renderError and believe that this is not a duplicate.

Expected Behavior

Calling app.renderError should be straight-forward and render the default error page with the new code that I provide it. Full code is below (scroll down).

I initially tried this:

return app.renderError(403, req, res, "/progress", req.query);

And then I realized that the first parameter is supposed to be an error object, so then I tried this:

res.statusCode = 403;
return app.renderError(null, req, res, "/progress", req.query);

This should simply render the default error page from Next.js with my error code and not bounce to another page on the next ping.

Current Behavior

Instead, what happens is that I see a brief glimpse of the expected error page with my 403 code in it, but on the next ping, it redirects to the /progress page but without an id param being passed down (because there isn't). Ideally, you should never see the /progress page if there is no id in the URL.

Steps to Reproduce (for bugs)

This is the code that I used:

const express = require("express");
const next = require("next");

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  server.get("/progress/:id?", (req, res) => {
    if (!req.params.id) {
      console.log("no id submitted");
      res.statusCode = 403;
      return app.renderError(null, req, res, "/progress", req.query);
    }
    const queryParams = Object.assign(req.query, req.params);
    return app.render(req, res, "/progress", queryParams);
  });

  server.get("*", (req, res) => handle(req, res));

  server.listen(port, (err) => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${port}`);
  });
});
  1. Use the above code in a file server.js.
  2. Run in dev mode by running a script that says node server.js.
  3. Run localhost:3000/progress/ (with no id in the path).
  4. Note that you get the correct error page, but on subsequent ping it redirects to the /progress page but with no ID passed down in its props.

Your Environment

Tech Version
next 3.0.6
node 8.4.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions