DEV Community

GreggHume
GreggHume

Posted on

Strapi: Create user via api

The functionality to create a user via api in Strapi 4 is already built in.
Its just that the route is different to the usual api routes.

Route to hit as POST:

// route to POST to
localhost:1337/api/auth/local/register

// body data to send
{
   "email": "test1@test3.com",
   "username": "test2",
   "password": "123456",
   "firstname": "Grey", // custom field (see below config)
   "lastname": "Joy", // custom field (see below config)
   "organisers": [1] // id or ids of a relation field (mine is called organisers)
}

// returns
{
  "jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NCwiaWF0IjoxNjk1MTQ1NDA3LCJleHAiOjE2OTc3Mzc0MDd9.9aUrYF4Ws1WCTDXHTFMU_7WUs0i5iLeqPdwubHM62mc",
  "user": {
    "id": 4,
    "username": "test2",
    "email": "test1@test3.com",
    "provider": "local",
    "confirmed": true,
    "blocked": false,
    "createdAt": "2023-09-19T17:43:27.406Z",
    "updatedAt": "2023-09-19T17:43:27.406Z",
    "firstname": "Grey",
    "lastname": "Joy",
    "role": {
      "id": 3,
      "name": "Customer",
      "description": "a logged in customer",
      "type": "customer",
      "createdAt": "2023-09-19T09:51:22.756Z",
      "updatedAt": "2023-09-19T09:51:22.756Z"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

If you added custom fields to your user you will need to enable them by adding a file to the config folder:

// ./config/plugins.js

module.exports = ({ env }) => ({
  "users-permissions": {
    config: {
      register: {
        // put the name of your added fields here
        allowedFields: ["firstname", "lastname", "organisers"],
      },
    },
  }
});
Enter fullscreen mode Exit fullscreen mode

Reference:
https://docs.strapi.io/dev-docs/plugins/users-permissions#registration

Top comments (0)