Next.js Discord

Discord Forum

Next Auth Redirect uri is invalid with multi tenant architecture

Unanswered
Spectacled bear posted this in #help-forum
Open in Discord
Spectacled bearOP
Hi, I'm implementing the multi tenancy architecture in my application and i'm facing one issue with next-auth. I'm using sign in functions to sign in for google and discord and im passing the callback url as localhost:3000 but Im getting an error saying redirect_uri mismatch.

I'm on page client.localhost:3000/login

Error
Request details: redirect_uri=http://client.localhost:3000/api/auth/callback/google flowName=GeneralOAuthFlow


Middleware code:
import { NextRequest, NextResponse } from 'next/server'

export const config = {
    matcher: [
        '/((?!_next/static|_next/image|favicon.ico|public/).*)', // Match all routes except these
        '/api/(.*)',
    ],
}

const allowedPaths = [
    '/api',
    '/assets',
    '/_next/static',
    '/_next/image',
    '/favicon.ico',
    '/public/',
]

export async function middleware(request: NextRequest) {
    const url = request.nextUrl

    const path = url.pathname

    if (allowedPaths.some((allowedPath) => path.startsWith(allowedPath))) return NextResponse.next()

    let protocol = url.protocol // http: or https:

    let hostname = request.headers.get('host') // client.localhost:3000
    console.log('XXXXXXXXXXXX', `${url.origin}${path}`)

    if (path.startsWith('/api')) {
        console.log('inside api')
        return NextResponse.rewrite(new URL(`${url.origin}${path}`))
    }

    const finalUrl = protocol + '//' + hostname // http://client.localhost:3000 or  http://localhost:3000

    if (finalUrl === process.env.SITE_URL) {
        return NextResponse.next()
    }

    if (hostname) hostname = hostname.replace(`.${url.host}`, ``) // client

    return NextResponse.rewrite(new URL(`/${hostname}${path}`, request.url))
}

7 Replies

Spectacled bearOP
Code to invoke sign-in

<ActionButton
                onClick={() =>
                    signIn('google', {
                        callbackUrl: '/test', // any random url to test
                    })
                }
                text='Log in with Google'

            />
Chinese Alligator
do you know where the /api/ part comes from? in the docs its using /api/ but i get redirect_url_mismatch with it unless i take it out
https://github.com/nextauthjs/next-auth-example
Chinese Alligator
i figured it out: uncommented the following in auth.ts
  // basePath: "/auth",
@Chinese Alligator i figured it out: uncommented the following in auth.ts // basePath: "/auth",
Spectacled bearOP
I'm not using this line in my route file.
Spectacled bearOP
Spectacled bearOP
Anyone?