DEV Community

GreggHume
GreggHume

Posted on

8

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

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs