3

I'm looking to use a conditional in the NextJS middleware.ts and I'm using an env variable to decide which parts of the matcher field will be. Either ["/folder/(.*)"] or ["/no-match"].

From what I understand, this is valid JavaScript since I get the expected result testing in an isolated page.

export { default } from "next-auth/middleware"

export const config = {
  matcher:
    process.env.NEXT_PUBLIC_AUTH_USERS === "true"
      ? ["/folder/(.*)"]
      : ["/no-match"],
}

NOTE: "true" because boolean env args are strings.

I get an error:

Unsupported node type "ConditionalExpression" at "config.matcher".
The default config will be used instead.
Read More - https://nextjs.org/docs/messages/invalid-page-config

It says conditionals not allowed so is there another way I can use this logic?

Change to one of the options works fine.

1 Answer 1

0

You can customize the authorized callback for a conditional check. On my side, I want to use an environment variable to skip logins if in development. I found this post after getting the same error you got.

See https://next-auth.js.org/configuration/nextjs#callbacks for more info.

In your case, you can do something like:

import {
  withAuth
} from "next-auth/middleware";

export default withAuth({
  callbacks: {
    authorized: ({
      token
    }) => !!token && process.env.NEXT_PUBLIC_AUTH_USERS === "true"
  },
}, );

export const config = {
  matcher: ["/folder/(.*)"]
}

Token will be set if user is logged in, otherwise will be null.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.