Next.js Discord

Discord Forum

NextAuth Experimental Advanced Initialization

Cyan posted this in #help-forum
Open in Discord

I'm currently using next-auth@experimental with route handlers. I want to implement NextAuth's advanced initialization but there is no documentation to do so for experimental. I want to use advanced initialization to store user IP and user-agent along with their session in the session table. We also need to be able to use the auth() wrapper in the middleware. Is there any examples of how to use advanced initialization with next-auth@experimental in route handlers?


4 Replies

Barbary Lion
You could do something like [this](
import type { NextApiRequest, NextApiResponse } from "next"
import NextAuth from "next-auth"

async function handler(req: NextApiRequest, res: NextApiResponse) {

  // Get the req info like IP
  const ip = req.headers['x-forwarded-for']
  return await NextAuth(req, res, {
    callbacks: {
      session({ session, token }) {
        // Use the IP here
        session.ip = ip
        return session
export {handler as GET, handler as POST}

The only drawback is that you cannot get the auth() function to wrap your middleware in, but it should give you a start maybe.
I got that far but I need the auth() wrapper for the middleware. This is what I had:

// api/auth/[...nextauth]/auth.ts
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  return NextAuth({
    // NextAuth options...

// api/auth/[...nextauth]/route.ts
export { handler as GET, handler as POST } from "./auth"

How can I expose the auth() wrapper so I can also use it in my middleware and still be able to get the IP and User-Agent via the request? Does anyone have an idea on how this can be achieved?
Barbary Lion
I have no clue, as extracting auth() from NextAuth, so like const { auth } = nextAuth({..}) is now dependent on request and response, so you cannot normally export it and use it in the middleware.

I hope someone else has an idea.