Untitled
unknown
javascript
2 years ago
2.6 kB
6
Indexable
I built a nextjs app, it is an image generation platform with AI, I want to limit signed in users to only send one image generation request at a time, so I don't want them to open the dashboard from multiple tabs and send simultaneous requests, how can I implement that? To prevent users from sending multiple image generation requests simultaneously, you can implement a combination of client-side and server-side checks. Here's a suggested approach: Client-side: Use localStorage or sessionStorage to store a flag indicating whether a request is in progress. Server-side: Implement a rate-limiting middleware to limit requests per user. Step 1: Client-side flag In your Next.js app, you can use localStorage or sessionStorage to store a flag when a user initiates an image generation request. This flag will help you determine if there's already a request in progress. javascript Copy code // When the user submits a request function handleRequestSubmission() { // Check if there's already a request in progress if (localStorage.getItem('requestInProgress') === 'true') { alert('You already have an image generation request in progress. Please wait until it completes.'); return; } // Set the flag and send the request localStorage.setItem('requestInProgress', 'true'); sendImageGenerationRequest(); } // When the request is completed function onRequestCompleted() { localStorage.removeItem('requestInProgress'); } Step 2: Server-side rate limiting To ensure users can't bypass the client-side restrictions by sending requests directly to the API, you should implement rate limiting on the server-side. You can use a package like express-rate-limit to limit requests per user. Install the package: npm install express-rate-limit Set up rate limiting in your API: javascript Copy code const rateLimit = require('express-rate-limit'); // Create a rate limiter with custom options const imageGenerationLimiter = rateLimit({ windowMs: 60 * 1000, // 1 minute window max: 1, // Limit each user to 1 request per windowMs message: 'You can only send one image generation request at a time. Please wait.', }); // Apply the rate limiter to your API route app.post('/api/generate-image', imageGenerationLimiter, async (req, res) => { // Your image generation logic here }); This approach combines both client-side and server-side checks to ensure that users can only send one image generation request at a time. Remember to adjust the rate limiting settings according to your desired limits and infrastructure capacity.
Editor is loading...