Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Auth.js · Function

getCsrfToken

getCsrfToken() asynchronously returns the current Auth.js CSRF token for state-changing requests such as authentication or session updates.

How it works

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.

Syntax

function getCsrfToken(): Promise<string>

Returns

Promise<string> containing the current CSRF token.

Key points

  • The function resolves to the currently available CSRF token.
  • Use the token for requests that mutate authentication or session state.
  • Typical protected operations include signing in, signing out, and updating a session.
  • Auth.js documents the double-submit-cookie pattern as its CSRF prevention mechanism.

Common mistakes

  • If the framework already supplies CSRF protection, the Auth.js CSRF endpoint may be disabled, so token retrieval can be unavailable.
  • Do not disable Auth.js CSRF protection casually; doing so can remove a defense against forged state-changing requests.

Example: Render 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.

When to use it

Include a token in a custom sign-in form

Custom authentication form

Protect a request that updates session state

Session mutation

Interview questions

QWhat does getCsrfToken return?

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.

QWhen should an application call getCsrfToken?

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.

QWhat is the function signature and how is it used?

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.

  • signIn
  • signOut
  • useSession
  • skipCSRFCheck

Source: React - Auth.js. Checked 2026-10-15.