Identify Users in a Cloudflare Worker by IP to Serve User-specific Data

Share this video with your friends

Send Tweet
Published 4 months ago
Updated 2 months ago

Our application works but there is one major flaw. Everyone sees the same to-do's. To make to-do's user-specific, we are going to link users' data to their IP addresses so people only see to-dos based on their IP address.

Instructor: [0:00] As a final exercise for this project, one interesting thing that I think really showcases how powerful Workers is, is adding a specific field that allows all of your todo list application data to be user-specific.

[0:13] Right now, we use the cache key data to represent the key that we look at when getting data and putting data in our KV namespace. Because we're using a consistent data key here, everyone that visits our application is going to be looking at the same todo list, which isn't super helpful for any practical use, say, if you wanted to share this todo list application with your friends or coworkers.

[0:36] In my initial Cloudflare Workers course, I showed that there's a lot of information inside of a request that we make available, things like location data, and even things like connecting IP addresses, which will provide a unique IP address per user, or at least per network. We can use our IP address to make our cache key specific to an IP address.

[0:57] Let's make a new variable called IP, and then say, request.headers.get to get a specific header from the request, in this case, cf-connecting-ip. This will represent an IP address that is connecting to this Workers function.

[1:16] Now what I'll do with that is, instead of just using data here, I'm going to replace this with a backtick string and say, data- and then interpolate this IP variable into it. I won't just be getting data from KV using the key data, it will be data-my IP, or your IP, depending on where you're connecting from.

[1:35] If I copy this code here, and then replace the corresponding cache key in my updateTodos function with the same code, I'll now have a specific set of data for each IP address that connects to this project. This means that you can use the application, your friends can use the application, and you'll have separate sets of todos that won't be tied together in any way.