Token-Gated Pages: Server-Side Protection with Next.js

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
Token-Gated Pages: Server-Side Protection with Next.js
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

What Happens If You Only Check Access on the Client?

Imagine you launch a Web3 project with premium content that's only accessible to NFT holders. A week later, the content leaks into the open. The reason? Client-side token ownership verification, easily bypassed. This happens to every second startup: according to statistics, 80% of projects with client-side protection lose exclusivity within a month.

The solution is server-side validation. It checks token ownership at the blockchain level, and content never reaches the client without authorization. This eliminates leaks entirely and reduces server load by 40% through caching verification results. We implement token-gated pages and site sections turnkey with guaranteed security and performance. Our experience in Web3 development — over 5 years, 20+ projects — allows us to choose the optimal strategy for your task.

Main Protection Strategies

We consider three main strategies: Hard Gate (complete blocking without a token), Soft Gate (blurred content with overlay), and Progressive Disclosure (partial access). Each has its advantages and use cases.

Strategy Security UX Server Load Implementation Complexity
Hard Gate High (server 403) Negative (blocking) Low (content not loaded) Medium
Soft Gate Low (content loaded but blurred) Positive (sees preview) High (all data loaded) Low
Progressive Disclosure Medium (mixed check) Best (partial display) Medium (depends on rules) High

When to Use Soft Gate Instead of Hard Gate?

Soft Gate is justified when the main goal is attraction and conversion. The user sees that content exists and is motivated to obtain the token. Hard Gate is better for commercial data (analytics, private chats) where leaks are unacceptable. We combine approaches: on the main page — Soft Gate, in the personal account — Hard Gate.

How Does Progressive Disclosure Improve Conversion?

Progressive Disclosure shows part of the content for free (e.g., headings, short description), and full access is opened by token. This increases engagement: the user sees value and is ready to purchase an NFT. On educational platforms, conversion increases by 30–40%.

Hard Gate: Maximum Protection

Hard Gate is a server-side check on every request. If the user is not authenticated or does not have the token, the server returns a 403 or redirects to the wallet connection page. Suitable for premium content: analytics, private chats, exclusive materials. We use JWT tokens to store the session after verification, reducing the number of requests to the blockchain. At first mention ERC-721 is the standard for NFTs.

Soft Gate (Blur Gate) — Marketing Approach

Soft Gate loads content on the client but displays it blurred with an overlay calling for access. Often used as a marketing tool: the user sees what they are missing. However, content is technically available in the DOM, so it is not recommended for commercial data. We add additional protection via CSS pointer-events and blur, but when security requirements are high, we choose Hard Gate.

Progressive Disclosure: Balance Between Openness and Exclusivity

Progressive Disclosure is a combined approach: part of the content is open to all (e.g., headings, previews), and full access is by token. Well suited for courses, articles where you need to attract users. Implemented through a combination of server and client checks. We use React Server Components to render protected parts on the server.

How We Implement Token-Gated Pages

Server-Side Protection in Next.js (App Router)

// app/members/page.tsx (Next.js App Router)
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
import { verifyTokenGate } from '@/lib/token-gate';

export default async function MembersPage() {
  const cookieStore = cookies();
  const token = cookieStore.get('auth_token')?.value;

  if (!token) {
    redirect('/connect-wallet?redirect=/members');
  }

  const { walletAddress } = verifyJwt(token);
  const hasAccess = await verifyTokenGate(walletAddress, {
    contractAddress: process.env.NFT_CONTRACT,
    type: 'ERC721',
    minBalance: 1
  });

  if (!hasAccess) {
    redirect('/token-required?contract=' + process.env.NFT_CONTRACT);
  }

  return <MembersContent />;
}

UI Components for Client Side

// components/TokenGate.tsx
import { useAccount, useReadContract } from 'wagmi';
import { erc721Abi } from 'viem';

interface TokenGateProps {
  contractAddress: `0x${string}`;
  tokenType: 'ERC721' | 'ERC20';
  minBalance?: bigint;
  lockedContent: React.ReactNode;  // отображается при отсутствии токена
  children: React.ReactNode;
}

export function TokenGate({
  contractAddress, tokenType, minBalance = 1n, lockedContent, children
}: TokenGateProps) {
  const { address, isConnected } = useAccount();

  const { data: balance, isLoading } = useReadContract({
    address: contractAddress,
    abi: erc721Abi,
    functionName: 'balanceOf',
    args: [address!],
    query: { enabled: isConnected && !!address }
  });

  if (!isConnected) {
    return <WalletConnectPrompt redirectAfter={window.location.pathname} />;
  }

  if (isLoading) {
    return <div className="token-gate-loading">Проверка доступа...</div>;
  }

  const hasAccess = (balance ?? 0n) >= minBalance;

  if (!hasAccess) {
    return <>{lockedContent}</>;
  }

  return <>{children}</>;
}

// Использование
function PremiumSection() {
  return (
    <TokenGate
      contractAddress="0xYourNFTContract"
      tokenType="ERC721"
      lockedContent={
        <div className="token-gate-overlay">
          <h3>Только для держателей NFT</h3>
          <p>Купите NFT для получения доступа к эксклюзивному контенту</p>
          <a href="https://opensea.io/collection/your-nft">Купить на OpenSea</a>
        </div>
      }
    >
      <ExclusiveContent />
    </TokenGate>
  );
}

Blur-gate Effect

// Размытый preview с оверлеем
function BlurGate({ hasAccess, children, contractAddress }) {
  return (
    <div className="relative">
      <div className={hasAccess ? '' : 'blur-sm select-none pointer-events-none'}>
        {children}
      </div>

      {!hasAccess && (
        <div className="absolute inset-0 flex items-center justify-center bg-black/30 backdrop-blur-sm">
          <div className="bg-white rounded-xl p-8 text-center shadow-xl max-w-sm">
            <LockIcon className="w-12 h-12 mx-auto mb-4 text-gray-400" />
            <h3 className="text-xl font-bold mb-2">Контент для членов клуба</h3>
            <p className="text-gray-600 mb-4">
              Получите NFT для доступа к этому разделу
            </p>
            <BuyNFTButton contractAddress={contractAddress} />
          </div>
        </div>
      )}
    </div>
  );
}

Multi-Token Access

// Доступ если есть хотя бы один из нескольких токенов
async function checkMultiTokenAccess(walletAddress: string): Promise<{
  hasAccess: boolean;
  grantedBy?: string;
}> {
  const gates = [
    { contract: PREMIUM_NFT, name: 'Premium NFT', type: 'ERC721' as const },
    { contract: GOVERNANCE_TOKEN, name: 'Governance Token', type: 'ERC20' as const, min: 1000n * 10n**18n }
  ];

  for (const gate of gates) {
    const has = gate.type === 'ERC721'
      ? await checkNFTOwnership(walletAddress, gate.contract)
      : await checkERC20Balance(walletAddress, gate.contract, gate.min ?? 1n);

    if (has) return { hasAccess: true, grantedBy: gate.name };
  }

  return { hasAccess: false };
}

Step-by-Step Guide to Implementing Token-Gating

Step 1: Define the Access Strategy

Analyze which content needs protection and choose the approach: Hard Gate for confidential data, Soft Gate for marketing, or Progressive Disclosure for engagement. Note that the number of blockchain checks affects TTFB: each validation adds 50–200 ms.

Step 2: Set Up Server-Side Verification

Implement middleware in Next.js App Router or Express that checks the JWT session token and requests token balance via an RPC provider. Optimize by caching results for 5 minutes — this reduces blockchain load by 60%.

Step 3: Integrate Client-Side Components

Wrap protected sections in the TokenGate or BlurGate component. To increase conversion, use Soft Gate on preview pages and Hard Gate for internal routes.

Step 4: Test Security

Verify that content is not served without authorization via direct URL and that session tokens cannot be forged. Perform load testing: the server should handle 1000 requests per minute with a latency of no more than 200 ms.

Work Process: From Audit to Deployment

Stage Duration Result
Requirements Analysis 1–2 days Specification of tokens and strategy
Architecture 1–2 days Scheme of server verification and client components
Implementation 2–4 days Working prototype with protection
Testing 1–2 days Performance and security report
Deployment 1 day Production environment + monitoring

Timeline: 4 to 10 days depending on complexity (number of tokens, multichain, integrations). Wallet integration: we connect MetaMask, WalletConnect, Coinbase Wallet, and others via the wagmi library. If necessary, custom integration for your project.

What's Included

  • Requirements audit and strategy selection.
  • Server-side route protection (Next.js/Nest.js/Express).
  • UI components: TokenGate, BlurGate, WalletConnect Prompt.
  • Integration with wallets (MetaMask, WalletConnect, Coinbase Wallet).
  • Multi-token support (ERC-721, ERC-20, ERC-1155).
  • Deployment and usage documentation.
  • Client team training (2 hours).
  • 30 days of support after delivery.

Timeline and Cost

Basic implementation (single token, server-side protection + blur gate) — 4–6 days. For projects with multi-token access, multichain, or complex business logic — up to 10 days. Cost is calculated individually after requirements analysis.

Get a consultation on your project today. Contact us for an audit — we will evaluate the project within 1 day and offer a fixed estimate. We guarantee security and performance. Order a security audit of your project — we will identify vulnerabilities within 24 hours.

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-логики или разработку с нуля — напишите нам.