Sitemap

Stripe: create user programmatically

2 min readNov 22, 2023

--

Creating a user in Strapi might seem like a straightforward task, but the lack of comprehensive documentation can transform this simple process into a frustrating ordeal. To assist fellow developers in saving time and maintaining a reference for future use, this guide will guide you through the steps of creating a user using the ‘plugin::users-permissions.user’.

Press enter or click to view image in full size
Photo by Claudio Schwarz on Unsplash

Import the auth module from “@strapi/admin/server/services/auth” to hash the user’s password.

//const auth = require("@strapi/admin/server/services/auth");
const bcrypt = require('bcryptjs');
const hashPassword = (password) => bcrypt.hash(password, 10);

Create a user object with the following properties

//const auth = require("@strapi/admin/server/services/auth");
const bcrypt = require('bcryptjs');
const hashPassword = (password) => bcrypt.hash(password, 10);

let user = await strapi.db.query("plugin::users-permissions.user").create({
data: {
username: "username",
email: "email@email.com",
confirmed: true,
role: 1,
provider: 'local',
created_by_id: 1,
updated_by_id: 1,
//password: await auth.hashPassword('password').
password: await hashPassword('password')
},
});

Now, keep attention to the data object:

    Get devinred 🎈’s stories in your inbox

    Join Medium for free to get updates from this writer.

  • username: The unique identifier for the user.
  • email: The user's email address.
  • confirmed: Set to true to indicate that the user's email address is verified.
  • role: The ID of the role to assign to the user.
  • provider: Set to 'local' to indicate a local user.
  • created_by_id: The ID of the user who created the new user.
  • updated_by_id: The ID of the user who last updated the new user.
  • password: The user's password, hashed using the auth module.

That’s all. Pay close attention to the created_by_id and updated_by_id properties. Without these values, your newly created user won't be able to log in.

Edit

To fix the error

./server/services/auth' is not defined by "exports"

use bcryptjs to hash the password.

--

--

devinred 🎈
devinred 🎈

Written by devinred 🎈

I'm interested in many things, but only briefly. Then, I need to switch things up - whether it's the project, language, or even keyboard https://devinred.com