0

I'm using Next.js with "Express.js" to serve authentication-protected web pages.

We have an auth middleware in our "server.js" defined as follows:

 server.use(
    /\/private((\/)?$|\/_next\/data\/.*)/, // exclude sub-path of /preferiti but include /private/_next/data/...
    authMiddleware(),
  );

The middleware calls our external authentication service; to avoid calling it also for static assets we have implemented a regexp that exclude sub-path of our page (private).

In your opinion, exists a more general way to say: "apply this middleware only for the web pages"?

user2354037
  • 195
  • 2
  • 8
  • Sorry to not answer the question but: why would you do that? I see a lot of people asking questions about custom servers: using a custom server is leaving Next.js "pit of success", it makes everything more difficult (hence the need to ask questions on Stack Overflow), and it leads you to a fully custom setup that makes it difficult for other people to help. To protect the page, you can use client-side patterns as usual. If you really really don't want to deliver the client code to unauthenticated users and have a very good reason to do so, you can rely on `getServerSideProps` to compute it. – Eric Burel Apr 07 '21 at 08:48
  • And to answer the question your Regexp sounds good to me. As an alternative I'd put the private pages into a subfolder if that makes sense in your app (eg if it mixes private and public pages), so you can isolate them (like `admin/`). Full answer for redirections: https://stackoverflow.com/questions/58173809/next-js-redirect-from-to-another-page/60616536#60616536 – Eric Burel Apr 07 '21 at 08:52
  • Yes, about to avoid to use custom server, is a good point but currently we have only this express middleware to check if user is authenticated (we must to use it). A more dynamic solution that I'm testing is this: `if (!req.path.includes('_next/static')) ` – user2354037 Apr 07 '21 at 09:08

0 Answers0