Skip to main content

Auth.js Endpoints

Auth.js provides several endpoints for authentication operations. This page documents the available endpoints and their usage.

Authentication Endpoints​

EndpointMethodDescription
/api/auth/signinGETDisplays the sign-in page with all configured providers
/api/auth/signin/:providerPOSTInitiates sign-in with the specified provider
/api/auth/callback/:providerGETCallback URL for OAuth providers to return to after authentication
/api/auth/signoutGETDisplays the sign-out page
/api/auth/signoutPOSTSigns the user out and invalidates their session
/api/auth/sessionGETReturns the current session data
/api/auth/csrfGETReturns a CSRF token for form submissions
/api/auth/providersGETReturns a list of configured providers

Session Management​

Auth.js uses JWT (JSON Web Tokens) for session management. The session can be accessed in your application using the useSession hook or the getServerSession function.

Client-Side Session Access​

import { useSession } from "next-auth/react"

export default function Component() {
const { data: session, status } = useSession()

if (status === "loading") {
return <p>Loading...</p>
}

if (status === "authenticated") {
return <p>Signed in as {session.user.email}</p>
}

return <p>Not signed in</p>
}

Server-Side Session Access​

import { getServerSession } from "next-auth"
import { auth } from "@/auth"

export async function getServerSideProps(context) {
const session = await getServerSession(context.req, context.auth)

if (!session) {
return {
redirect: {
destination: '/api/auth/signin',
permanent: false,
},
}
}

return {
props: {
session,
},
}
}

CORS Configuration​

When using Auth.js with a separate frontend application, you need to configure CORS to allow cross-origin requests. This is done in the next.config.js file:

/** @type {import("next").NextConfig} */
module.exports = {
async headers() {
return [
{
source: '/api/auth/:path*',
headers: [
{ key: 'Access-Control-Allow-Credentials', value: 'true' },
{ key: 'Access-Control-Allow-Origin', value: 'https://your-frontend-domain.com' },
{ key: 'Access-Control-Allow-Methods', value: 'GET,POST,OPTIONS' },
{ key: 'Access-Control-Allow-Headers', value: 'X-CSRF-Token,X-Requested-With,Accept,Accept-Version,Content-Length,Content-MD5,Content-Type,Date,X-Api-Version' },
],
},
]
},
}