Next.js Discord

Discord Forum

Advice for next-auth with App Router for magic links authentication

Answered
Pink salmon posted this in #help-forum
Open in Discord
Pink salmonOP
Hello! I've successfully implemented next-auth with Pages router, using email provider and magic links. Now, I want to convert the whole application to App Router.

After converting the app/api/auth/[...nextauth]/route.js I end with:

export { handler as GET, handler as POST }

instead of export AuthOptions

I'm confused about how can I proceed to import this in the restricted.js file, where it asks for AuthOptions:

import { getServerSession } from "next-auth/next"
import { authOptions } from "../../app/api/auth/[...nextauth]"

/* eslint import/no-anonymous-default-export: [2, {"allowArrowFunction": true}] */
export default async (req, res) => {
  const session = await getServerSession(req, res, authOptions)
  if (session) {
    res.send({
      content:
        "This is protected content. You can access this content because you are signed in.",
    })
  } else {
    res.send({
      error: "You must be signed in to view the protected content on this page.",
    })
  }
}


The visual behavior is that when I Signout, the application isn't redirected to the black screen with email input and button in the middle (from the magic link next-auth example)

EDIT: I managed to fix this part by following the link below:

https://github.com/tfutada/zenn-nextjs/tree/main/app

By moving options to its own file and referencing the options where needed.

Now I'm getting a bunch of:

- error Error: React Context is unavailable in Server Components
at stringify (<anonymous>)
null
Answered by Pink salmon
EDIT: I managed to fix following lots of advices in this discord, but basically, I got rid of SessionProvider and useSession, and used getServerSession
View full answer

1 Reply

Pink salmonOP
EDIT: I managed to fix following lots of advices in this discord, but basically, I got rid of SessionProvider and useSession, and used getServerSession
Answer