Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
3 replies
EQ

NextJS middleware

Hello,

In the middleware file, I want to check if the user is authenticated and allowed to visit specific pages.

Currently how I do it is as following:
// Some page
const Page = () => { ... }

Page.auth = {
  route: "/page"
  protectFromNonAuth: {
    roles: ["ADMIN"]
  }
}

// NextJS Middleware file
const routes = [
  {
    route: "/page"
    protectFromNonAuth: {
      roles: ["ADMIN"]
    }
  }
]

export const middleware = async (req: NextRequest) => {
  // Get the current route and find it in the routes array and check if user has
  // permission to visit the page.
}
This works but what I don't like about it is that I now have double code for the same thing.

When I import the auth functionality from all the pages, so like
const routes = [
  Page.auth,
  OtherPage.auth
];
it works in dev mode but when building for production, it says Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime because I import those auth from the pages.

Does someone know a better and cleaner way of doing this? I have quite some pages and I don't want to forgot also adding the auth in the routes array in the middleware.
Was this page helpful?