Include a token in a custom sign-in form
Custom authentication form
Auth.js · Function
getCsrfToken() asynchronously returns the current Auth.js CSRF token for state-changing requests such as authentication or session updates.
Call getCsrfToken without arguments to asynchronously obtain the current Auth.js CSRF token. Include the returned value when constructing a request that changes authentication or session state, such as signing in, signing out, or updating a session.
function getCsrfToken(): Promise<string>Promise<string> containing the current CSRF token.
import { getCsrfToken } from "next-auth/react";
export default async function Page() {
const csrfToken = await getCsrfToken();
return <input name="csrfToken" type="hidden" value={csrfToken} />;
}Fetches the current token and places it in a hidden form field for a state-changing request.
Custom authentication form
Session mutation
It is an asynchronous zero-argument function whose result is a Promise<string>. The string is the current CSRF token used for state-changing requests.
Follow-up: Why is the token needed? Auth.js uses the double-submit-cookie technique, comparing the submitted token with the value associated with the cookie.
Use it when a request changes state, including authentication actions or session updates. Retrieve the token with await and submit it as part of the request or form data.
Follow-up: What should happen if Auth.js CSRF protection is disabled? A CSRF response may be unavailable and the corresponding endpoint can return 404.
The function takes no parameters, so its signature is getCsrfToken(): Promise<string>. The caller must await the promise before using the token value.
Follow-up: What broader security mechanism does this support? It supports CSRF prevention through a double-submit cookie rather than accepting an unverified state-changing request.
signInsignOutuseSessionskipCSRFCheck