Custom Registration and Login in Strapi

Strapi has built-in login and registration functions which can be found in node_modules. For many simple projects these built-in functions are sufficient, but what if we want to edit the functions or

Author:

Strapi has built-in login and registration functions which can be found in node_modules. For many simple projects these built-in functions are sufficient, but what if we want to edit the functions or add something to them (such as API request)? In this article I will present you two possible solutions.

1. Calling Strapi function from our own API

This is the easiest and probably the best method when we don't want to edit Strapi functions, but add something to them.

We start by making our own API:

strapi generate

Then we select "api" and give it its name.

To call a Strapi function from node_modules in case of registration we use this code:

await strapi.plugin('users-permissions').controllers.auth.register(ctx);

And in case of login we use this code:

await strapi.plugin('users-permissions').controllers.auth.callback(ctx);

Editing API response

If we simply call Strapi functions we will get the default responses. To edit our custom api response after calling the function from node_modules we can use ".then()" method and edit the body request. For example, my customLogin function from <api-name>/controllers:


export default {
 customLogin: async (ctx) => {
  const customData = ...yourcode...
  await strapi.plugin('users-permissions').controllers.auth.callback(ctx)
  .then(() => {
   ctx.body.customData = customData
   })
  }
};

2. Copy the function from node_modules to your own api and edit it

If part of a particular Strapi function doesn't suit us, we can simply copy and edit it. To do this we create our own api and then copy the code from this location (location in Strapi v4):

"node_modules/@strapi/plugin-users/permissions/server/controllers/auth.js"

In this file we will find the functions "register" and "callback" (for login). These functions also use other functions from node_modules, so we need to copy them as well.

Disadvantage of this way

This method has the obvious disadvantage that we keep the same, or very similar code in two different places, so I recommend using it only as a last resort. In the vast majority of cases, editing the function in the Strapi admin panel or using the first method from this article will be more optimal.

Published by
Linkedin
May 2023