How to access get user IP after/before registration ...in order to be able to store it alongside the user in DB

I want to get the user IP and store it in DB immediately after user registration.

I know that I can use model LifeCycles like (afterCreate or beforeCreate) but the problem is that there
I don’t have access to (ctx.request) …

And I think to write this logic in users_permissions Controller…
But how to (create/customize) this controller without affecting its own plugin logic?
Any hint will be useful …thanks :wink:

1 Like

The best option that wouldn’t require messing with the users-permissions plugin would be to create a custom middleware that runs as the response payload is being sent back to the user.

Depending on where you place your logic will determine when the logic will run (basically before or after the await next()

module.exports = strapi => {
  return {
    initialize() {
      strapi.app.use(async (ctx, next) => {
        await next();

        // You'll probably want to log the ctx.request.route and do some if() to check the route for only registrations or whatever

        console.log(ctx.headers); // If using proxy, IP will be in an x-forwarded-for header
        console.log(ctx.ip);
        console.log(ctx.ips);

       // From here you would have access to the ctx.response.body to grab the users ID
       // And could do something like:
       await strapi.query('user', 'users-permissions').update({ id: ctx.response.body.id}, { ipaddress: ctx.ip});
       // or put it anywhere else
      });
    },
  };
};

Can’t promise the above example will actually work, just my suggestion on it. You can read more about middlewares here: Configurations - Strapi Developer Documentation

If you want to see an example middleware that might be useful to check what is available to middlewares I created a small debug middleware that will log out some stuff (they are all disabled by default so you’ll have to adjust the settings).

1 Like

Thanks for the idea… I’ll use it.

@Gherciu_Gheorghe just checking back with you to see if you were able to implement something

Hi @DMehaffy , Yes, I just created a custom endpoint which I’m calling from UI after the user is registered…so in this way, I have access to the request and all stuff I need… because from my point of view seems more cleaner to have 2 endpoints (one for registration and one for data setup after registration) instead of writing a middleware or rewriting things in users_permissions plugin…but yeah your idea is also good.

2 Likes