Functions and Identity

If you have Identity enabled on your site, your serverless functions get access to the Identity instance and to Identity user claims in the context object. You can also trigger serverless functions via Identity events.

Access Identity info via clientContext

If an Identity service is active for a site, serverless functions running on that site have access to an identity and a user object in the clientContext. You can access the client context with JavaScript like this:

export function(event, context, callback) {
  const {identity, user} = context.clientContext;
  // Do stuff...

Visit our docs on Go functions to learn how to access the clientContext with Go.

The user object is present if the function request has an Authorization: Bearer <token> header with a valid JWT from the Identity instance. In this case the object will contain the decoded claims.

The identity object has url and token attributes. The URL is the endpoint for the underlying GoTrue API powering the Identity service. The token attribute is a short-lived admin token that can be used to make requests as an admin to the GoTrue API.

Trigger serverless functions on Identity events

You can trigger serverless function calls when certain Identity events happen, like when a user signs up. The following events are currently available:

  • identity-validate: Triggered when an Identity user tries to sign up via Identity.
  • identity-signup: Triggered when an Identity user signs up via Netlify Identity. (Note: this fires for only email+password signups, not for signups via external providers e.g. Google/GitHub)
  • identity-login: Triggered when an Identity user logs in via Netlify Identity

To set a serverless function to trigger on one of these events, match the name of the function file to the name of the event. For example, to trigger a serverless function on identity-login events, name the function file identity-login.js.

If you return a status other than 200 or 204 from one of these event functions, the signup or login will be blocked.

The payload in the body of an Identity event function looks like:

  "event": "login|signup|validate",
  "user": {
    # an Identity user object

If your serverless function returns a 200, you can also return a JSON object with new user_metadata or app_metadata for the Identity user. For example, if you return:

{"app_metadata": {"roles": ["admin"]}}

The value of the Identity user's app metadata will be replaced with the above.