Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nextjs deployment succeeded but landing page fails with Code: MIDDLEWARE_INVOCATION_FAILED #1680

Closed
3 tasks done
chaotic-justice opened this issue Jan 26, 2025 · 2 comments
Closed
3 tasks done
Labels
bug Something isn't working needs-isolation unconfirmed Needs triage.

Comments

@chaotic-justice
Copy link

Description

middleware:

import { auth } from "@/auth"
import { routing } from "@/i18n/routing"
import { isAdmin } from "@/lib/utils"
import createIntlMiddleware from "next-intl/middleware"
import { NextRequest, NextResponse } from "next/server"

interface AppRouteHandlerFnContext {
  params?: Record<string, string | string[]>
}

const intlMiddleware = createIntlMiddleware({
  locales: routing.locales,
  defaultLocale: routing.defaultLocale,
  localePrefix: routing.localePrefix,
})

const homePages = ["/", "/signin"]
const authPages = ["/workers", "/images-uploader"]
const adminPages = ["/secret"]

const getPathnameRegex = (pages: string[]) => RegExp(`^(/(${routing.locales.join("|")}))?(${pages.flatMap((p) => (p === "/" ? ["", "/"] : p)).join("|")})/?$`, "i")

const homePathnameRegex = getPathnameRegex(homePages)
const authPathnameRegex = getPathnameRegex(authPages)
const adminPathnameRegex = getPathnameRegex(adminPages)

const authMiddleware = (request: NextRequest, ctx: AppRouteHandlerFnContext) => {
  return auth((req) => {
    const path = req.nextUrl.pathname
    const session = req.auth

    const isHomePage = homePathnameRegex.test(path)
    const isProtected = authPathnameRegex.test(path)
    const isAdminPage = adminPathnameRegex.test(path)

    if (session) {
      if (isHomePage) {
        return NextResponse.redirect(new URL("/workers", req.url))
      } else if (isAdminPage) {
        if (!isAdmin(session.user.email)) {
          console.log("not an admin", session.user.email)
          return NextResponse.redirect(new URL("/not-found", req.url))
        }
      }
    } else {
      if (isProtected || isAdminPage) {
        return NextResponse.redirect(new URL("/signin", req.url))
      }
    }

    return intlMiddleware(request)
  })(request, ctx)
}

export const middleware = (request: NextRequest, ctx: AppRouteHandlerFnContext): NextResponse => {
  if (request.nextUrl.pathname.startsWith("/auth")) {
    return NextResponse.next()
  }

  return authMiddleware(request, ctx) as NextResponse
}

export const config = {
  matcher: ["/((?!api|_next|_vercel|.*\\..*).*)"],
}

nextauth config:

import NextAuth, { DefaultSession } from "next-auth"
import Google from "next-auth/providers/google"

declare module "next-auth" {
  interface Session {
    user: {
      address?: string
      provider?: string
    } & DefaultSession["user"]
    error?: string
  }
}

export const { handlers, signIn, signOut, auth } = NextAuth({
  secret: process.env.AUTH_SECRET,
  callbacks: {
    // @ts-ignore
    async signIn({ user, account }) {
      //Allow OAuth without email verification
      if (account?.provider !== "credentials") return true
      // email verification logic here
      return true
    },
    // @ts-ignore
    async session({ token, session }) {
      if (token.userId && session.user) {
        session.user.id = token.userId as string
      }

      return session
    },
    async jwt({ token }: { token: any }) {
      return token
    },
  },
  providers: [
    Google({
      authorization: { params: { access_type: "offline", prompt: "consent" } },
    }),
  ],
})

error messages from logs

Image

Verifications

Mandatory reproduction URL

https://github.com/chaotic-justice/excel-stunning-pork

Reproduction description

Steps to reproduce:

  1. Open reproduction
  2. Click on …
  3. See error: …

Expected behaviour

it works locally, deploys succesfully abut landing page will throw error

@chaotic-justice chaotic-justice added bug Something isn't working unconfirmed Needs triage. labels Jan 26, 2025
Copy link

Thank you for your report!

From the currently available context in this issue, it's unclear wether the erroneous behavior is caused by Next.js, next-intl or a 3rd party library that you're using. Please isolate the issue further to be sure that the issue is caused by next-intl. When in doubt, please search on the Next.js issue tracker or related resources of 3rd party libraries you might be using.

If you're able to isolate the issue to next-intl, please provide a minimal reproduction that ideally doesn't involve any 3rd party libraries or alternatively demonstrates that next-intl is causing the issue.

Thank you for your understanding!

@chaotic-justice
Copy link
Author

cloned a repo off your app-router-with-next-auth example, deployed it, it works perfectly. i think this issue may be unrelated to next-intl. closign this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working needs-isolation unconfirmed Needs triage.
Projects
None yet
Development

No branches or pull requests

2 participants