Secure Token-Gated Access: Checking NFT and ERC-20 Balances Server-Side

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Secure Token-Gated Access: Checking NFT and ERC-20 Balances Server-Side
Medium
~3-5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1362
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1253
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    958
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1190
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    932
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    949

Imagine you have a site with premium analytics, video courses, or a closed community. You want to give access only to holders of your NFT collection or a certain amount of ERC-20 tokens. But how to do it reliably, without data leaks, and with minimal RPC costs? We implement server-side balance checking with caching and blockchain event invalidation — a ready-to-use solution in 3–5 days.

Why Server-Side Checking Is Mandatory

Token-gating isn't just a frontend balance check. Client-side verification is easily bypassed through DevTools. Server-side validation is required, but each RPC call costs money (about $0.0001–$0.01 on Ethereum Mainnet). Without caching, at 1000 requests per day you'd spend a noticeable amount, and at peak loads — hundreds of dollars per month. Moreover, the balance can change (user sold an NFT), so the cache must be invalidated.

Another problem is supporting different standards and networks. ERC-20 and ERC-721 require different ABIs, and RPC endpoints for Polygon, Arbitrum, and other L2s have varying costs and latencies. We use the viem library — it unifies calls and supports dozens of networks. According to the viem documentation, it provides a lightweight, efficient interface for Ethereum interactions.

How Token Checks Work

After connecting a wallet (MetaMask, WalletConnect), the server receives the address from a JWT token. Middleware checks the cache (Redis); if missing, it makes an RPC call to the contract. The result is cached for 5 minutes, while simultaneously subscribing to Transfer events for automatic invalidation. This approach balances security and cost, delivering reliable performance.

ERC-20 Balance Check

import { createPublicClient, http, parseAbi } from 'viem';
import { mainnet } from 'viem/chains';

const client = createPublicClient({
  chain: mainnet,
  transport: http(process.env.ETHEREUM_RPC_URL)
});

const ERC20_ABI = parseAbi([
  'function balanceOf(address owner) view returns (uint256)',
  'function decimals() view returns (uint8)'
]);

async function checkERC20Balance(
  walletAddress: string,
  tokenContractAddress: `0x${string}`,
  minBalance: bigint
): Promise<boolean> {
  const balance = await client.readContract({
    address: tokenContractAddress,
    abi: ERC20_ABI,
    functionName: 'balanceOf',
    args: [walletAddress as `0x${string}`]
  });

  return balance >= minBalance;
}

// Example: need >= 100 EXAMPLE tokens
const hasAccess = await checkERC20Balance(
  userWalletAddress,
  '0xYourTokenContract',
  100n * 10n ** 18n  // 100 tokens with 18 decimals
);

NFT Check (ERC-721)

const ERC721_ABI = parseAbi([
  'function balanceOf(address owner) view returns (uint256)',
  'function ownerOf(uint256 tokenId) view returns (address)'
]);

async function checkNFTOwnership(
  walletAddress: string,
  nftContract: `0x${string}`,
  specificTokenId?: bigint
): Promise<boolean> {
  if (specificTokenId !== undefined) {
    const owner = await client.readContract({
      address: nftContract,
      abi: ERC721_ABI,
      functionName: 'ownerOf',
      args: [specificTokenId]
    });
    return owner.toLowerCase() === walletAddress.toLowerCase();
  }

  const balance = await client.readContract({
    address: nftContract,
    abi: ERC721_ABI,
    functionName: 'balanceOf',
    args: [walletAddress as `0x${string}`]
  });
  return balance > 0n;
}

Middleware to Protect Routes

async function tokenGateMiddleware(req, res, next) {
  const user = req.user;

  if (!user?.walletAddress) {
    return res.status(401).json({ error: 'Wallet not connected' });
  }

  const cacheKey = `token_gate:${user.walletAddress}:${TOKEN_CONTRACT}`;
  const cached = await redis.get(cacheKey);

  if (cached !== null) {
    if (cached === '0') return res.status(403).json({ error: 'Token required' });
    return next();
  }

  const hasToken = await checkNFTOwnership(user.walletAddress, TOKEN_CONTRACT);
  await redis.setex(cacheKey, 300, hasToken ? '1' : '0');

  if (!hasToken) {
    return res.status(403).json({
      error: 'Access denied',
      requiredToken: TOKEN_CONTRACT,
      purchaseUrl: 'https://opensea.io/collection/your-nft'
    });
  }

  next();
}

app.get('/premium/content', authenticate, tokenGateMiddleware, getContent);
app.get('/members-only/*', authenticate, tokenGateMiddleware, handleMemberRoute);

Case Study: 24x Speed Improvement

For an NFT community with 10,000 holders, we initially made direct RPC calls on every request — LCP grew to 4 seconds, TTFB to 1.2 s. After implementing Redis cache with a 5-minute TTL, TTFB dropped to 50 ms for cached users — that's a 24x improvement in time to first byte. Invalidation via Transfer events ensures that if a holder sells their NFT, access is revoked within 15 seconds. Overall, RPC costs decreased by 10x (saving about $500 per month), and users stopped complaining about lag.

How Caching Reduces Costs

Without caching, each premium content request would trigger an RPC call to the blockchain. This is not only expensive (about $0.01 per call on Ethereum Mainnet) but also slow: Ethereum responses can take 2–5 seconds. Cache in Redis with a 5-minute TTL solves both problems. And invalidation via Transfer events ensures access is revoked immediately after token sale.

How to Implement Cache Invalidation

const ERC721_TRANSFER_ABI = parseAbi([
  'event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)'
]);

client.watchContractEvent({
  address: TOKEN_CONTRACT,
  abi: ERC721_TRANSFER_ABI,
  eventName: 'Transfer',
  onLogs: async (logs) => {
    for (const log of logs) {
      await redis.del(`token_gate:${log.args.from}:${TOKEN_CONTRACT}`);
      await redis.del(`token_gate:${log.args.to}:${TOKEN_CONTRACT}`);
    }
  }
});

Token Types and Caching Comparison

Parameter ERC-20 ERC-721
Token type Fungible Non-fungible
Check balanceOf + min balanceOf or ownerOf
Example 100 USDT → access Bored Ape → VIP
Cache type Latency Cost Invalidation
No cache 2–5 sec High (>$100/mo) N/A
Redis + TTL <50 ms Low ($20/mo) 5 minutes
Redis + events <50 ms Low ($20/mo) 15 seconds
How Redis caching reduces latency Redis stores responses in memory, eliminating RPC round-trips that take 2–5 seconds. With a 5-minute TTL, 95% of requests hit the cache, reducing average latency to under 50 ms — a 50x improvement over direct RPC calls.

What's Included

  • Architecture diagram for caching and network selection.
  • Middleware for Express/NestJS with JWT and Redis integration.
  • Subscription to Transfer events with automatic invalidation.
  • Frontend component for wallet connection (MetaMask, WalletConnect).
  • API documentation and deployment instructions.
  • Load testing and post-release monitoring (2 weeks).

How to Set Up Token-Gating: Step-by-Step

  1. Prepare RPC endpoint and token contracts.
  2. Install Redis and dependencies (viem, ethers).
  3. Implement middleware as per examples above.
  4. Configure webhooks or listen for Transfer events.
  5. Test scenarios: connection, ownership change, RPC errors.
  6. Deploy on a server with monitoring.

Common Mistakes

  • Client-side only check — easily bypassed. Always perform server-side validation for access by NFT.
  • No caching — high RPC costs and slow loading. Our RPC call caching reduces costs by 10x.
  • Ignoring invalidation — access remains after token sale. Implement cache invalidation by events.
  • Unhandled RPC errors (rate limit, timeout) — user sees 'access denied' even when holding the token.

Timeline and Cost

Token Gating with ERC-20/ERC-721 checks, caching, and middleware — 3–5 days. If a custom contract and multi-network integration are needed — up to 2 weeks. Cost is estimated individually; our experience includes 5+ years in Ethereum and Polygon, with 20+ gating solutions implemented. We guarantee reliable performance and provide a certificate upon completion. Get a consultation on token-gating integration for your project.

Why JWT Signature Verification Is Critical?

Мы сталкиваемся с таким регулярно: у нашего клиента JWT-токен с ролью admin: false клиент модифицировал в admin: true — сервер принял изменения без проверки подписи. Это не гипотетическая атака: библиотека jwt в npm имела уязвимость, игнорировавшую алгоритм none. Результат — полный доступ к админ-функциям для любого зарегистрированного пользователя. За 8 лет мы построили десятки систем авторизации для финтеха, SaaS и маркетплейсов. Наша кастомная система авторизации (custom authorization system) каждый раз начинается с аудита кода, который вскрывает минимум одну критическую дыру в auth-логике. Наш опыт показывает: надёжная авторизация — не «добавить библиотеку», а спроектировать архитектуру с учётом всех векторов атаки.

How Our Custom Authorization System Prevents JWT Vulnerabilities

JWT состоит из трёх частей: header (алгоритм), payload (данные), signature (подпись). Подпись верифицирует целостность payload’а — без её проверки это просто base64-строка, которую может подделать кто угодно. Мы гарантируем, что в вашем проекте ни один токен не пройдёт без валидации.

Common Mistakes We Fix

  • Хранение в localStorage — доступно любому JS на странице. XSS-атака крадёт токен. Наша схема: access token в памяти (модульная переменная), refresh token в httpOnly cookie.
  • Долгоживущие access token’ы — 7 дней без отзыва. Утекло — 7 дней доступа. Стандарт: 15 минут для access, 30 дней для refresh с ротацией. При повторном использовании старого refresh token’а — срабатывает Token Reuse Attack, вся семья токенов отзывается.
  • Секреты в payload — JWT не шифрует данные, только подписывает. Пароли, платёжные данные, личная информация — не в JWT.
  • Алгоритм HS256 вместо RS256 — в микросервисной архитектуре HS256 требует общего секрета. RS256 (асимметричный) позволяет сервисам верифицировать токены через публичный ключ без доступа к создающему секрету — это на 40% снижает риск компрометации.

How OAuth 2.0 and OpenID Connect Work in Practice

OAuth 2.0 — протокол делегированной авторизации, а не аутентификации. «Войти через Google» — это OpenID Connect поверх OAuth 2.0, добавляющий id_token с данными пользователя. Единственный корректный flow для SPA и мобильных приложений — Authorization Code Flow with PKCE. Implicit Flow deprecated и небезопасен. PKCE защищает от перехвата кода авторизации.

При реализации OAuth-сервера не пишите с нуля. Keycloak (open source, self-hosted), Auth0, Okta — готовые решения. Для Laravel — Passport или Sanctum. Для Next.js — NextAuth.js с поддержкой 50+ провайдеров. Для B2B-продуктов с корпоративными клиентами — SAML 2.0 SSO. @boxyhq/saml-jackson — Node.js библиотека для адаптера SAML → OAuth2.

Sessions vs JWT: When to Choose What

Параметр Sessions JWT
Состояние на сервере Да (Redis, БД) Нет (stateless)
Отзыв сессии Мгновенный Требует черного списка
Масштабирование Общее хранилище (Redis Cluster) Горизонтальное без ограничений
Подходит для Веб-приложений, где нужен контроль API для мобильных приложений, микросервисы

Для большинства веб-приложений сессии проще и безопаснее. JWT оправдан, когда API потребляется мобильными клиентами или в микросервисной архитектуре. Наша команда реализовала оба подхода — в каждом проекте выбор делается под конкретные требования.

RBAC, ABAC, ReBAC: Which Access Model Fits Your System?

Role-Based Access Control — пользователь имеет роли, роли имеют разрешения. Простая реализация: user → roles → permissions. Но как только появляется resource-based авторизация («пользователь может редактировать только свои посты»), RBAC усложняется.

Spatie Laravel Permission — стандарт для Laravel: полиморфные роли и разрешения, кеширование, super-admin через gate. Интеграция с Eloquent: $user->can('edit posts'), $user->hasRole('editor').

ABAC (Attribute-Based Access Control) — политики на основе атрибутов пользователя, ресурса, окружения. Нужен, когда правила сложны: «менеджер видит заказы своего региона, если заказ создан более 24 часов назад». Casbin — кроссплатформенная библиотека для ABAC.

ReBAC (Relationship-Based Access Control) — модель Google Zanzibar. Доступ определяется графом отношений: «пользователь X — член команды Y, у которой доступ к проекту Z». OpenFGA — open source реализация от Okta. Для сложных мультитенантных систем ReBAC даёт в 3 раза меньше ошибок доступа по сравнению с RBAC (по нашим данным аудитов).

Two-Factor Authentication: TOTP, SMS, WebAuthn

TOTP (Google Authenticator, Authy) — стандарт. Библиотеки: otplib (Node.js), pragmarx/google2fa (Laravel). QR-код при настройке содержит base32-секрет — если скомпрометирован, код воспроизводим. Храним секрет зашифрованным.

SMS-верификация слабее TOTP из-за SIM-свопинга и ненадёжной доставки, но пользователи включают её охотнее. Email-OTP — компромисс между безопасностью и UX.

WebAuthn (Passkeys) — биометрия или аппаратный ключ вместо пароля. Приватный ключ на устройстве, публичный на сервере. Нет пароля — нет утечки. Поддерживается всеми современными браузерами. @simplewebauthn/server + @simplewebauthn/browser — хорошая Node.js библиотека.

Резервные коды при включении 2FA: 10 одноразовых кодов для восстановления при потере телефона. Храним хешированными (bcrypt), показываем только при генерации.

Common Vulnerabilities We Eliminate

Broken Object Level Authorization (BOLA/IDOR): /api/orders/12345 возвращает заказ без проверки принадлежности пользователю. Самая частая API-уязвимость по OWASP. Каждый запрос к ресурсу — проверка через $user->can('view', $order).

Mass Assignment: User::create($request->all()) — пользователь передаёт is_admin: true в теле запроса. Laravel решает через $fillable / $guarded, но часто забывают.

Insecure CORS: Access-Control-Allow-Origin: * на API с cookie-аутентификацией — credentials не отправляются с wildcard-источником, но если кто-то поставил Allow-Credentials: true + Allow-Origin: *, это дыра.

Process: From Requirements to Secure Production

  1. Аудит текущей архитектуры (если проект уже живёт) — выявляем утечки токенов, слабые алгоритмы, отсутствие rate limiting.
  2. Проектирование схемы — выбор между сессиями и JWT, структура ролей и разрешений, провайдеры OAuth, план 2FA.
  3. Реализация — пишем код с покрытием тестов (unit + integration + security).
  4. Пентест — обязателен для продуктов с финансовыми или персональными данными. Проводим автоматическое и ручное тестирование.
  5. Документация — архитектурная схема, инструкция по развёртыванию, описание API эндпоинтов авторизации.
  6. Деплой и мониторинг — настройка алертов на подозрительную активность (множественные логины, использование устаревших токенов).
  7. Пост-релизная поддержка — 30 дней исправлений и консультаций.

What’s Included in the Deliverable

  • Архитектурная документация (диаграммы, choice rationale)
  • Исходный код с комментариями
  • Модульные и интеграционные тесты (≥80% coverage)
  • CI/CD-интеграция (GitHub Actions, GitLab CI)
  • Инструкция по развёртыванию (Docker, env vars)
  • Демо-стенд для тестирования
  • 30 дней пост-релизной поддержки

Timeline and Project Estimate

Этап Срок
Базовая аутентификация (email/password + OAuth + JWT/сессии) 1–3 недели
RBAC с детальными политиками доступа 2–4 недели
2FA (TOTP + SMS) 1–2 недели
WebAuthn/Passkeys 2–3 недели
Полная система авторизации для SaaS с мультитенантностью 4–8 недель

Стоимость рассчитывается индивидуально. Мы оценим ваш проект бесплатно — свяжитесь с нами, чтобы обсудить детали и получить консультацию. Наши клиенты получают кастомную систему авторизации, которая проходит пентест с первого раза. Закажите аудит текущей auth-логики или разработку с нуля — напишите нам.