Testing netlify identity triggers

So your working on a RedWood app and have opted to use netlify identity. That’s great, allowing netlify to do the heavy lifting of your Auth, while still letting you hook into particular events by triggering “identity events”. This is covered a little in the RBAC cookbook, but here I want to talk specifically about using these events to write to your db, such as creating a new user. Here’s an example.

// src/functions/identity-signup.js
import { createUser } from 'src/services/users/users.js'
export const handler = async (req, _context) => {
  const body = JSON.parse(req.body)
  const user = body.user
  const email = user.email
  if (body.event === 'signup') {
    await createUser({input: {
      email,
      bio: 'default bio'
    }})
  }
  return { statusCode: 200 }
}

We’re importing one of our services, but of course db can be imported directly. Now that we’re ready to test our code we want to avoid deploying for the sole purpose of testing it, because even if you have a staging environment setup where test data can be created, it’s still a slow development cycle and burns up build minutes.

First a point of clarification, by testing, I mean manual verification checks done while in development, not automated tests, though some of this information could be leveraged for that too.

We can use netlify’s cli to invoke these functions. Detailed information is on the netlify community forum, but in short the steps are:

# Install the cli
yarn add netlify-cli -g

# Rebuild api after your last changes to /functions
yarn rw build api

# Invoke your function with the CLI, pointing it to the rw dev port
netlify functions:invoke identity-signup --port 8910

Netlify will invoke the function and include relevant test data as if it were being called in production. For example here’s the body it passed through.

    {
      event: 'signup',
      user: {
        id: '1111a1a1-a11a-1111-aa11-aaa11111a11a',
        aud: '',
        role: '',
        email: 'foo@trust-this-company.com',
        app_metadata: { provider: 'email' },
        user_metadata: { full_name: 'Test Person' },
        created_at: '2020-10-21T09:43:23.992Z',
        update_at: '2020-10-21T09:43:23.992Z'
      }
    }

The reason you need to rebuild the api after each change is because the netlify-cli uses your netlify.toml to determine where the functions are, and this should point to your build directory functions = "api/dist/functions"

You should now see changes you expect to data in your local db.

Thanks to @danny and @dthyresson for giving me a hand with this one.

2 Likes

@Irev-Dev

Thanks for writing this info up! Super helpful.

Any chance you can add the steps to test invoke identity-signup to:

I assume the signin/login event works the same, right?

1 Like