import { NextAuthHandler } from "../core" ; import { setCookie , detectHost } from "./utils" ; import type { GetServerSidePropsContext , NextApiRequest , NextApiResponse , } from "next" ; import type { NextAuthOptions , Session } from ".." ; import type { NextAuthAction , NextAuthRequest , NextAuthResponse , } from "../lib/types" ; async function NextAuthNextHandler ( req , res , options ) { const { nextauth , ... query } = req . query ; const handler = await NextAuthHandler ( { req : { host : detectHost ( req . headers [ "x-forwarded-host" ] ) , body : req . body , query , cookies : req . cookies , headers : req . headers , method : req . method , action : nextauth ?. [ 0 ] as NextAuthAction , providerId : nextauth ?. [ 1 ] , error : ( req . query . error as string | undefined ) ?? nextauth ?. [ 1 ] , } , options , } ) ; res . status ( handler . status ?? 200 ) ; handler . cookies ?. forEach ( ( cookie ) => setCookie ( res , cookie ) ) ; handler . headers ?. forEach ( ( h ) => res . setHeader ( h . key , h . value ) ) ; if ( handler . redirect ) { if ( req . body ?. json !== "true" ) { res . status ( 302 ) . setHeader ( "Location" , handler . redirect ) ; return res . end ( ) ; } return res . json ( { url : handler . redirect } ) ; } return res . send ( handler . body ) ; } function NextAuth ( options ) ; function NextAuth ( req , res , options ) ; /** Tha main entry point to next-auth */ function NextAuth ( ... args ) { if ( args . length === 1 ) { return async ( req , res ) => await NextAuthNextHandler ( req , res , args [ 0 ] ) ; } return NextAuthNextHandler ( args [ 0 ] , args [ 1 ] , args [ 2 ] ) ; } export default NextAuth ; export async function getServerSession ( context , options ) { const session = await NextAuthHandler < Session | { } > ( { options , req : { host : detectHost ( context . req . headers [ "x-forwarded-host" ] ) , action : "session" , method : "GET" , cookies : context . req . cookies , headers : context . req . headers , } , } ) ; const { body , cookies } = session ; cookies ?. forEach ( ( cookie ) => setCookie ( context . res , cookie ) ) ; if ( body && Object . keys ( body ) . length ) return body as Session ; return null ; } declare global { namespace NodeJS { interface ProcessEnv { NEXTAUTH_URL ? : string ; VERCEL ? : "1" ; } } }