Is there a way to store ammount of requests on a netlify site?

Hello world,

I want to keep track of request count on my site:

And do something special if a user
is the 100 000th or smt request, but netlify
analytics is an overkill for this imho
and I’m kinda uncomfortable collecting
that much about users so I don’t know

Any way to keep track of the ammount?
I tried netlify functions but no luck

Can’t think of anything that works,

Functions I tried:

  • This doesn’t work
"use strict";

let c = 0;

exports.handler = () => {
    return {
        statusCode: 200,
        body: `Hello request ${c++}!`,
    };
}

And

  • This works but pretty sure it resets every deploy
"use strict";

if (!process.env.RQ)
    process.env.RQ = 0;

exports.handler = () => {
    process.env.RQ = parseInt(process.env.RQ) + 1;

    return {
        statusCode: 200,
        body: `Hello request ${process.env.RQ}!`,
    };
}

I don’t know, maybe I should do the second on
like req.ari-web.xyz and never deploy there?

But maybe there are better solutions, anything
better?

Thanks in advance :slight_smile:

Btw, if anyone wants to run this, this is how I
did it:

  1. Make a directory
  2. Go into that directory
  3. Make a directory called .netlify/functions
  4. Add this to netlify.toml
[functions]
    directory = ".netlify/functions"
  1. Add any of the snippets into .netlify/functions/a.js
  2. Run netlify dev (netlify cli)
  3. Go to http://127.0.0.1:8888/.netlify/functions/a

Hey @B00bleaTea

Data in a function (like the counter in your first example) lasts only about as long as the function runs. So the could would always return 1 because it starts at 0 every time.

The second attempt won’t work as it is not possible to set an environment variable from a function.

If you wanted an out-of-the-box solution, there is likely many hit counter services out there (though they may collection more than just a necessary user data.) Should you wish to follow the route of doing it yourself, you would need to store the counter elsewhere. With Supabase (Postgres) it is possible to increment a value via a function call. Upstash is another service (Redis) for data storage which may work well too (I’ve only used it for retrieving data in a function, not for putting, so cannot say for certain.)

3 Likes