Handle relative callback paths
Allow a post-authentication path such as /dashboard while resolving it against the site's base URL.
Auth.js · Function
The redirect callback controls where Auth.js sends users after callback-URL redirects, such as sign-in or sign-out. Return the requested destination when it meets your policy, or a safe fallback such as baseUrl.
The redirect callback runs when Auth.js sends a user to a callback URL during sign-in or sign-out. It receives the requested URL and the configured base URL, and must return the destination string; the default policy permits only URLs on the origin, while the callback can customize that policy.
redirect: (params) => Awaitable<string>| Name | Type | Description |
|---|---|---|
baseUrl | string | Default base URL of the site; can be used as a fallback. |
url | string | Callback URL provided by the client. |
Awaitable<string>
baseUrl as the canonical site destination or as the fallback for rejected URLs.url to evaluate the destination requested by the client.export const { handlers, auth } = NextAuth({
callbacks: {
async redirect({ url, baseUrl }) {
if (url.startsWith("/")) return `${baseUrl}${url}`
if (new URL(url).origin === baseUrl) return url
return baseUrl
},
},
})Configures Auth.js to accept relative destinations and same-origin absolute URLs while sending other destinations to the site base URL.
Allow a post-authentication path such as /dashboard while resolving it against the site's base URL.
Permit absolute callback URLs only when their origin matches the configured site.
Send unapproved destinations to the configured site rather than honoring them.
It is an asynchronous callback with the signature (params) => Awaitable<string>. Auth.js invokes it whenever a user is redirected to a callback URL, including sign-in and sign-out, and the returned string is the destination.
Follow-up: What inputs does it receive? It receives url, supplied by the client as the callback URL, and baseUrl, the site's default base URL.
The callback receives url and baseUrl. url is the client-provided callback URL, while baseUrl is the site's default base URL and can serve as a fallback.
Follow-up: How can a callback safely handle relative URLs? Prefix a leading-slash path with baseUrl before returning it.
A common policy accepts paths beginning with /, accepts absolute URLs whose origin equals baseUrl, and returns baseUrl for everything else. This preserves relative and same-origin navigation while rejecting other destinations.
Follow-up: Why reject other origins? Falling back to baseUrl prevents the callback from authorizing destinations outside the configured site origin.
callbackscallbackUrlbaseUrlAwaitable