MAISON CODE .
/ Security · Middleware · Token Gating · Membership

Gatekeeping Middleware: Token-Gating and Memberships

How to build "NFT Access" or "VIP Only" collections using Edge Middleware in Remix. Blocking requests before they hit the server.

AB
Alex B.
Gatekeeping Middleware: Token-Gating and Memberships

You launch a “Friends & Family” sale. You email the link. Someone posts it on Reddit. 10,000 people raid your stock. You need Gatekeeping. The logic must happen at the Edge. If the user is not allowed, do not even render the page.

The Edge Middleware Pattern

In Remix/Next.js, Middleware runs on every request.

// app/entry.server.tsx (or middleware.ts)
import { redirect } from '@remix-run/node';

export async function checkAccess(request, user) {
  const url = new URL(request.url);
  
  // 1. Check if route is protected
  if (url.pathname.startsWith('/collection/vip')) {
    
    // 2. Check Login
    if (!user) throw redirect('/account/login');
    
    // 3. Check Tag/Token
    const tags = user.tags || [];
    const hasVipTag = tags.includes('VIP_TIER_1');
    const hasNft = await checkWallet(user.wallet, 'BORED_APE');
    
    if (!hasVipTag && !hasNft) {
      throw redirect('/pages/access-denied');
    }
  }
}

Token Gating (Web3)

For NFT brands, the “Login” is a Wallet Connect. We use SIWE (Sign In With Ethereum).

  1. User clicks “Connect Wallet”.
  2. Signs a nonce.
  3. Server verifies signature.
  4. Server queries Blockchain Node (Alchemy/Infura): “Does Wallet X own Token Y?”
  5. If yes, issue Session Cookie.

Password Protection (Simple)

Sometimes you just need a password for the collection. Do not use Shopify’s global password page. Build a Scoped Password. Store the password hash in the Collection Metafield. User enters password -> Verify Hash -> Set Cookie collection_access_123=true -> Allow access.

Geo-Gating

“This product cannot be sold in California.” (Regulatory). Check request.cf.region (Cloudflare) or request.geo.city (Vercel). If region === 'CA', hide the “Add to Cart” button or redirect.

5. Role Based Access Control (RBAC) at the Edge

“Admins can see /dashboard. Users cannot.” Usually, you check this in the Server Component. But that wastes CPU. Check it in Middleware. Store roles in the JWT (user.roles = ['admin']). Middleware decodes the JWT (ignoring signature verification for speed, or verifying using Edge-compatible crypto). If role != admin, return 403 Forbidden instantly. This protects your backend API from unauthorized probing.

6. Bot Protection (Cloudflare Turnstile)

Middleware is the perfect place to stop bots. If User-Agent is HeadlessChrome, block. If cf-bot-score < 30, block. We inject Cloudflare Turnstile (Smart Captcha) specifically for suspicious requests. The normal user sees nothing. The bot sees a challenge. This happens before your database is even touched.

8. Server-Side A/B Testing

Client-side A/B testing (Google Optimize) causes “Flicker”. The user sees the old headline for 0.5s, then it swaps. Middleware solves this.

  1. Request comes in.
  2. Middleware checks cookie_bucket. If empty, assign bucket=B.
  3. Rewrite request to /variants/home-b.
  4. Server renders Variant B.
  5. User sees Variant B instantly. Zero flicker. SEO safe (if canonicals are managed).

9. Personalized Pricing at the Edge

“VIP Users get 20% off.” If you do this in Client JS, the hacker just changes the logic. If you do it in Middleware, it is secure.

  1. Middleware sees user_tier=vip.
  2. Middleware injects header x-pricing-tier: vip.
  3. Origin Server renders $80 instead of $100. The HTML arrives with the correct price. The user cannot manipulate it.

10. DDoS Mitigation at the Application Layer

Network DDoS is handled by Cloudflare. Application DDoS (Layer 7) is harder. “Search for ‘a’ 1000 times a second.” (Kills the DB). Middleware is the filter. We implement Token Bucket Rate Limiting per IP before Remix rendering. const allowed = await rateLimit.check(ip, 10, "10s"); If they exceed 10 requests in 10 seconds, return 429 Too Many Requests. Your rendering server never even wakes up.

11. The Queue (Virtual Waiting Room)

For “Hyped Drops” (Yeezy/Supreme), no server can handle the spike. Middleware redirects traffic to a Virtual Queue (Queue-it or Custom Redis).

  1. Check queue_token. Missing?
  2. Redirect to /queue.
  3. User waits. WebSocket updates position “You are #5000”.
  4. User reaches front. Redirect to /product?token=xyz.
  5. Middleware validates token. Allows access for 10 minutes. This flattens the traffic curve from a “Spike” to a “Plateau”.

12. HMAC Signing for B2B

If you have a B2B store, you often have a “Portal” link from an ERP. User clicks link in NetSuite -> Logged into Shopify. How do you secure this link? HMAC (Hash-based Message Authentication Code). The link contains ?user=123&timestamp=17000000&signature=abc.... Middleware verifies the signature using a shared secret. If timestamp is older than 5 minutes, reject. This allows “Passwordless” login that is cryptographically secure.

Why Maison Code Discusses This

At Maison Code, we view Middleware as the Shield. It is the first line of defense. We don’t leave your specific business logic exposed in client-side JS. We move complexity to the Edge. We have built “Token Gated” stores for NFT projects and “VIP Tiers” for luxury fashion houses. We know how to block the bots while rolling out the red carpet for the VIPs.

13. Advanced Bot Detection (Heuristics)

Bots are getting smarter. They execute JS. They pass Captchas (using farms). We need Behavioral Analysis at the Edge.

  1. Mouse Movement: Bots move in straight lines. Humans move in curves.
  2. Time on Page: Bots buy in 2 seconds. Humans take 20 seconds.
  3. Request Headers: Bots often have mismatched User-Agent and Sec-CH-UA. We use Cloudflare Worker logic to score these requests. Score < 10? Silent Redirect to a “Honeypot” checkout that charges them but ships nothing. This wastes their money and discourages them from attacking you again.

14. Geo-Fencing for License Compliance

You sell Nike. You are allowed to sell in EU, but not US. The “Address Picker” validation is too late. The US customer sees the product, adds to cart, and gets rejected at checkout. They are angry. Edge Geo-Fencing hides the product based on IP. If cf-ipcountry == 'US', the product page returns 404. The user never knows it exists. This protects your Vendor License Agreement and prevents “Grey Market” export capability.

15. The Middleware Checklist (Launch Readiness)

Don’t deploy middleware without checking these:

  1. Fail Open vs Fail Closed: If Middleware errors, do you block everyone or let everyone in? (Default: Fail Closed for security).
  2. Timeout: Set 50ms timeout. If KV is slow, don’t hang the page.
  3. Region Check: Tested via VPN from blocked country?
  4. Bypass Token: Do you have a ?token=admin_bypass query param for emergency access?
  5. Cache Rules: Ensure Vary: Cookie is set so you don’t cache the “Access Denied” page for everyone.
  6. Logging: Log every block to Datadog.
  7. User Agent: Whitelist Googlebot (User-Agent check).
  8. Rate Limit: Is the limit per IP or per Session?
  9. Static Assets: Bypass middleware for .jpg, .css, .js.
  10. Exception Handling: Try/Catch block around everything.
  11. Cold Start: Verify WASM cold start is < 10ms.
  12. Cost: Monitor invocations. Middleware runs on every request.
  13. Redirect Loop: Ensure you don’t redirect to a protected page.
  14. Mobile App: Does your Middleware break the iOS app API calls?
  15. Sitemap: Don’t hide sitemap.xml.

16. Conclusion

Gatekeeping creates Scarcity. Scarcity creates Value. But the Gate must be secure. Hiding a button via CSS (display: none) is not security. Anyone can Inspect Element. Middleware is the only way. It is fast, invisible, and unbreakable.


Need exclusive drops?

We engineer high-security access control systems.

Hire our Architects.