createToken()
Creates a new M2M token for the given machine. Must be authenticated by a Machine Secret Key.
Returns the created M2MToken object.
function createToken(params?: CreateM2MTokenParams): Promise<M2MToken>- Name
-
minRemainingTtlSeconds? - Type
number- Description
Enables server-side token reuse for opaque tokens. Only applies to opaque tokens (
token_format: 'opaque'). JWT tokens (token_format: 'jwt') are stateless and are never deduplicated. When set, if a non-revoked, non-expired M2M token already exists for this machine with identicalclaimsandscopesand at least this many seconds of remaining lifetime, that existing token is returned and no new token is minted. Use this when caching tokens in application memory across requests is impractical — for example, in serverless functions, short-lived job workers, or autoscaling containers that churn faster than the token TTL. Pooling at the server collapses many redundant create calls into reuse of a single live token, which is the recommended pattern for high-volume M2M traffic. Must be strictly less than the effective token lifetime — that is,seconds_until_expirationwhen provided, or the machine's default TTL otherwise. A value greater than or equal to the lifetime is rejected with a400error, since no freshly-minted token would ever satisfy the requirement.
- Name
-
tokenFormat? - Type
"opaque" | "jwt"- Description
The format of the M2M token to create. Defaults to
'opaque'. Set to'jwt'to create a JSON Web Token that can be verified locally without a network request. For a detailed comparison of the two formats, see Token formats.
const m2mToken = await clerkClient.m2m.createToken()
console.log(m2mToken)By default, createToken() creates an . To create a instead, pass tokenFormat: 'jwt':
const m2mToken = await clerkClient.m2m.createToken({
tokenFormat: 'jwt',
})
console.log(m2mToken)While it is strongly recommended to use environment variables for security, if you need to pass in the machine secret key directly rather than using an environment variable, you can do so by passing it as an argument to the createToken() method, as shown in the following example:
const m2mToken = await clerkClient.m2m.createToken({
machineSecretKey: 'ak_xxx',
})
console.log(m2mToken)Backend API (BAPI) endpoint
This method in the SDK is a wrapper around the BAPI endpoint POST/m2m_tokens. See the BAPI reference for more information.
Feedback
Last updated on