Extending /auth/local/register endpoint with custom logic

System Information
  • Strapi Version: 4.1.11
  • Operating System: macOS
  • Database: PostgreSQL
  • Node Version: v14.19.2

Hi!

I am not sure what the best practice is to reach my goal:

In my registration process I have a checkbox “register to newsletter”. When a new user ticks this box I want to do some API call, after successful registration to an external service to put the user on my mailing list.

So basically I want to hook into the logic of /auth/local/register. I do not want to touch the core logic, just want to execute some custom code after its done.

  • Is it best to override the register controller? And when yes, how?
  • Should I create a custom middleware for this? And again: When yes, how?

I would appreciate some feedback with code example or link to a fitting reference.

nico

Screenshot 2022-06-06 at 08.58.37

Create the strapi-server.js file like in the screenshot.
Use this code:

module.exports = (plugin) => {
  plugin.controllers.user["me"] = async (ctx) => {} //basically override any thing you want including services
}

i still try to find solve of same problem…

It doesn’t work :frowning:

Hi @Konstantin_Cube
I solved my case by creating a custom middleware. To do so do the following:

  1. create a file with a name by your choice in src/middlewares/yourfile.js
  2. In this file: Hook into Account creation with some code in the created file like this:
module.exports = () => {
  return async (ctx, next) => {
    await next();
    // only if path was register with newsletter param and it was successfull. Then we will put user in the mailing list.
    if (ctx.request.url === '/api/auth/local/register?newsletter=true' && ctx.response.status === 200) {
      const email = ctx.response.body.user.email;
      const name = ctx.response.body.user.nickname;
      // we do NOT await this. it has nothing to with account creation and should not block it. just a side effect.
      registerToNewsletter(email, name);
    }
  };
};
  1. Enable your middleware in src/config/middlewares.js
    f.e. like this: (See Reference: Middlewares configuration - Strapi Developer Docs)
module.exports = [
  // The array is pre-populated with internal, built-in middlewares, prefixed by `strapi::`
  'strapi::errors',
  'strapi::security',
  'strapi::cors',
   // ...
  'global::yourfile'
]
3 Likes

What file is this code in?

I updated my example. File name above.

1 Like