#Using middleware with NextAuth can't redirect out of the sign in page after logging in

11 messages · Page 1 of 1 (latest)

limber coyote
#

Hi guys, new here, so I'm not sure what I'm doing wrong. Basically, without the middleware file, the authentication is working and I'm getting the user ID, email (using Google as provider) after I log in.

This is my api/auth/[...nextauth]/route.ts file:

import NextAuth from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'
import clientPromise from '@/lib/mongodb'
import { MongoDBAdapter } from '@next-auth/mongodb-adapter'

const handler = NextAuth({
    secret: process.env.NEXTAUTH_SECRET,
    providers: [
        GoogleProvider({
            clientId: process.env.GOOGLE_ID!,
            clientSecret: process.env.GOOGLE_SECRET!
        })
    ],
    adapter: MongoDBAdapter(clientPromise),
})

export { handler as GET, handler as POST }

And this is my middleware file:

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

export const config = {
    matcher: [
        '/',
        '/api/auth/signin',
        '/api/products',
        '/api/upload',
        '/api/events',
        '/products',
        '/products/new',
        '/products/edit',
        '/events'
    ]
}

With this, all of those pages are locked and when I sign in with Google, I get back to the same page for signin (http://localhost:3000/api/auth/signin?callbackUrl=%2Fproducts). When going manually to localhost:3000, I still get redirected to sign in, so I'm guessing somehow the session is not being saved or something. But without the middleware it's working and I'm getting the data for the logged in user.

I've wrapped my layout with a SessionProvider. I'm not sure what I'm missing. Can you please help?

Much appreciated!

twilit sunBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

wary atlas
#

remove '/api/auth/signin', from the list

limber coyote
wary atlas
#

you need to exclude auth.js path like this.

export const config = {
    matcher: ["/((?!register|api|login).*)"], 
};
#

wait

limber coyote
#

also, it's loading from the database when no user is logged in, but I'll worry about that later 😄 first I need to actually be able to login after I protect the pages with middleware

limber coyote
#

can someone please give any tips and ideas how to fix this? thanks

kindred estuary
limber coyote