The waiting room is useful when you want to limit the number of active visitors to your website so as not to overload your resources.
In our implementation, you will be able to set a maximum number of active visitors. There will two parameters to control the traffic:
Max website capacity: Max number of visitors in the website at the same time?
Max session timeout: Max number of seconds that a visitor can stay idle
Step 1: Project Setup
Create a Next.js app:
Install upstash-redis:
Step 2: Implementation
Vercel supports Edge functions via Next.js middleware. So we will add _middleware.ts under pages/api/. The middleware code intercepts all requests made to /api. For different configurations see here.
Update pages/api/_middleware.ts as below:
We use Upstash Redis as the state store to keep the active user sessions. Thanks to its REST API, upstash-redis is compatible with Vercel Edge functions.
You need to create a Global database from the Upstash console. Copy and paste the REST token and REST URL from the console. The Redis database should be empty and used by only this application.
Also set TOTAL_ACTIVE_USERS and SESSION_DURATION_SECONDS depending on your own requirements.
The application creates a unique id for new visitors and sets it as a cookie and pushes it to Redis. So the next time, the application checks if the visitor has already a session checking Redis. While inserting to Redis, it sets an expiration time as session idle timeout. If the number of sessions exceeds the max-capacity, the new user is forwarded to the waiting room page.
You can update waiting_room_html to customize the waiting room page.
You can update the getDefaultResponse() method to forward to your own page using the NextResponse.
Step 3: Run and Deploy
Run the application locally by npm run dev. You may want to set 1 to TOTAL_ACTIVE_USERS and open the page (http://localhost:3000/api/hello) in different browsers to easily test the waiting room.
You can deploy your application to Vercel by
vercel deploy –prod
Vercel will run the _middleware.ts in edge locations to minimize the latency globally.
Conclusion
This tutorial showcases how easy it is to build a dynamic application at edge thanks to Vercel and Upstash. Check our examples for more examples.