Restrict access to content on your website to NFT Holders in Solana!

Overview

NFT Gated Website Solana

This project demonstrates how you can restrict content on your website to only those users who own an NFT from your collection.

We use an NFT Drop contract to enable users to claim one of the NFTs, and serve users the restricted content if they have at least one of the NFTs claimed.

Tools:

  • Solana SDK: To access the nft drop contract for claiming and checking the user's NFTs
  • Auth: To ask users to sign a message and verify they own the wallet they claim to be, while on the server-side.

Using This Template

Create a project using this example:

npx thirdweb create --template nft-gated-website-solana
  • Create an NFT Drop contract on solana using the dashboard.
  • Update the information in the yourDetails.ts file to use your contract address and auth domain name.
  • Add your wallet's private key as an environment variable in a .env.local file called PRIVATE_KEY:
PRIVATE_KEY=your-wallet-private-key

How It Works

Using Auth, we can verify a user's identity on the server-side, by asking them to sign a message and verify they own the wallet they claim to be, and validating the signature.

When we verified the user's identity on the server-side, we check their wallet to see if they have an NFT from our collection. We can then serve different content and restrict what pages they can access based on their NFT balance.

function MyApp({ Component, pageProps }) {
  return (
    <ThirdwebProvider
      authConfig={{
        authUrl: "/api/auth",
        domain: domainName,
        loginRedirect: "/",
      }}
      network={network}
    >
      <WalletModalProvider>
        <Component {...pageProps} />
      </WalletModalProvider>
    </ThirdwebProvider>
  );
}

export default MyApp;

Next, we need to create a configuration file that contains our wallet's private key (used to generate messages for users to sign) and our site's domain name:

This file is called auth.config.ts and is at the root of the project.

import { ThirdwebAuth } from "@thirdweb-dev/auth/next/solana";
import { domainName } from "./const/yourDetails";

export const { ThirdwebAuthHandler, getUser } = ThirdwebAuth({
  privateKey: process.env.PRIVATE_KEY as string,
  domain: domainName,
});

Finally, we have a catch-all API route called pages/api/auth/[...thirdweb].ts, which exports the ThirdwebAuthHandler to manage all of the required auth endpoints like login and logout.

import { ThirdwebAuthHandler } from "../../../auth.config";

export default ThirdwebAuthHandler();

Restricting Access

To begin with, the user will reach the website with no authentication.

When they try to access the restricted page (the / route), we use getServerSideProps to check two things:

  1. If the user is currently authenticated (using getUser).
  2. If the user's wallet has at least one NFT from our collection.

If either of these checks is false, we redirect the user to the /login page before they are allowed to access the restricted page.

Let's break that down into steps:

Setting Up the Auth SDK

Inside the _app.tsx file, we configure the Auth SDK in the ThirdwebProvider component that wraps our application, allowing us to use the hooks of the SDK throughout our application:

Checking For Authentication Token

First, we check if this user has already been authenticated.

If this is the first time the user has visited the website, they will not have an access_token cookie.

// This gets called on every request
export async function getServerSideProps(context) {
  const user = await getUser(context.req);

  if (!user) {
    return {
      redirect: {
        destination: "/login",
        permanent: false,
      },
    };
  }

  // ...
}

If the user is not authenticated, then we don't check the user's wallet balance; we just immediately redirect them to the /login page.

If there is a detected user from getUser, we can then check their balance.

Checking Wallet Balance

Now we're ready to check the user's wallet balance.

const program = await sdk.getNFTDrop(programAddress);
const nfts = await program?.getAllClaimed();

const hasNFT = nfts?.some((nft) => nft.owner === user.address);

Here's our final check, if the user hasNFT is false, we redirect them to the /login page.

if (!hasNFT) {
  return {
    redirect: {
      destination: "/login",
      permanent: false,
    },
  };
}

If the user gets past these checks, then we allow them to view the restricted page.

// Finally, return the props
return {
  props: {},
};

Signing In

We've now successfully restricted access to our home page, now let's explore the /login page.

First, we ask the user to connect their wallet with the WalletMultiButton

const { publicKey } = useWallet();

{
  !publicKey && <WalletMultiButton />;
}

Once an address is detected from the useAddress hook, we show them the Sign In button:

const { user } = useUser();

{
  publicKey && !user && (
    <button className={styles.button} onClick={() => login()}>
      Login
    </button>
  );
}

The Sign In button calls the login function that we're importing from the Auth SDK:

import { useLogin, useUser } from "@thirdweb-dev/react/solana";

const login = useLogin();

Inside the _app.tsx file, we configured the redirect users to the / route after they successfully sign in:

function MyApp({ Component, pageProps }) {
  return (
    <ThirdwebProvider
      desiredChainId={activeChainId}
      authConfig={{
        domain: domainName,
        authUrl: "/api/auth",
        loginRedirect: "/", // redirect users to the home page after they successfully sign in
      }}
    >
      <Component {...pageProps} />
    </ThirdwebProvider>
  );
}

export default MyApp;

Once the user has authenticated (signed the message), they are redirected to the home page /, and the getServersideProps logic runs again. Checking to see if they have an NFT.

Join our Discord!

For any questions, suggestions, join our discord at https://discord.gg/thirdweb.

You might also like...

Complete Open Source Front End Candy Machine V2 Minter dAPP Built For The Frog Nation NFT Solana Project. Built With React, Candy Machine V2, Typescript

Complete Open Source Front End Candy Machine V2 Minter dAPP Built For The Frog Nation NFT Solana Project. Built With React, Candy Machine V2, Typescript

Complete Open Source Front End Candy Machine V2 Minter dAPP Built For The Frog Nation NFT Solana Project. Built With React, Candy Machine V2, Typescript

Sep 24, 2022

NFT vending machine proof of concept built on Solana Pay, Metaplex, Phantom Mobile and Next.js.

Solana NFT Vending Machine This is a proof of concept of an NFT vending machine built using Solana Pay, Metaplex, Phantom Mobile, and Next.js. This wa

Dec 15, 2022

NFT stacking frontend completion using web3 on solana for client Nelson project.

NFT stacking frontend completion using web3 on solana for client Nelson project.

Dec 16, 2022

A new, simple NFT standard for Solana

New Solana NFT Standard Current Issues The current NFT spec is pretty bad for a few reasons: every NFT requires multiple accounts (3+) the token accou

Oct 20, 2022

Best Solana NFT Wallet Drainer/Stealer/Grabber Made with ❤️

Best Solana NFT Wallet Drainer/Stealer/Grabber Made with ❤️

📩 You need to host it on a real website for it to work (recommended: Hostinger, Netlify, Vercel) To Buy The Full Clean & deobfuscated Scripts Or For

Dec 6, 2022

a cobbled together alternative UI to launchdarkly, allowing read/write access via LD API access token

a cobbled together alternative UI to launchdarkly, allowing read/write access via LD API access token

discount-launchdarkly a cobbled together alternative UI to launchdarkly, allowing read/write access via LD API access token setup make sure you have a

Oct 19, 2022

Create your own custom NFT minting page using thirdweb's NFT Drop contract

Customizable NFT Drop Minting Page In this example, you can create your own NFT Drop minting page just by customising the template with your branding,

Dec 24, 2022

NFT Game Starter Project: https://github.com/buildspace/buildspace-nft-game-starter

Running React on Repl.it React is a popular JavaScript library for building user interfaces. Vite is a blazing fast frontend build tool that includes

Feb 11, 2022

Dead simple program to upload NFT data to IPFS via nft.storage

Dead simple program to upload NFT data to IPFS via nft.storage

NFTP The simplest way to publish files and folders to IPFS, with one command. 100% FREE to upload as much files as you want, powered by nft.storage. N

Dec 11, 2022
Yet another library for generating NFT artwork, uploading NFT assets and metadata to IPFS, deploying NFT smart contracts, and minting NFT collections

eznft Yet another library for generating NFT artwork, uploading NFT assets and metadata to IPFS, deploying NFT smart contracts, and minting NFT collec

null 3 Sep 21, 2022
Candy Shop is a JavaScript library that allows DAOs, NFT projects and anyone to create an NFT marketplace on Solana in minutes!

Candy Shop (IN BETA) Intro Candy Shop is a JavaScript library that allows DAOs, NFT projects and anyone to create an NFT marketplace on Solana in minu

LIQNFT 111 Dec 15, 2022
🐲 Epic NFTs [UI] - Proyecto que te permitirá conectar tu billetera y acuñar un NFT, podrás revender el NFT en OpenSea. El NFT en sí se puede personalizar

?? Epic NFTs [UI] El proyecto se encuentra deployado en Vercel para que puedan verlo e interactuar con él, toda crítica o comentario se agradece, pued

Braian D. Vaylet 17 Oct 22, 2022
Fullstack Dynamic NFT Mini Game built using 💎 Diamond Standard [EIP 2535] 🏃‍♀️Players can use Hero NFT to battle against Thanos ⚔ Heroes can be Healed by staking their NFT 🛡

?? Fullstack Dynamic NFT Mini Game ?? ?? Using Diamond Standard Play On ?? ?? ⏩ http://diamond-dapp.vercel.app/ Project Description ?? Fullstack Dynam

Shiva Shanmuganathan 21 Dec 23, 2022
NFT Marketplace framework to build standalone NFT marketplace or inApp/inGame NFT marketplace

NFT Marketplace This project is a decentalized NFT Marketplace framework which is to be the baseline for you to build standalone NFT marketplace or in

Reddio, inc. 14 Dec 19, 2022
An example of an NFT Gated Website for thirdweb's NFT Gated Website Guide

NFT Gated Website "One of the more dynamic use cases for NFTs is using them as a membership pass to the NFT holders. Let’s assume you want to create a

thirdweb examples 80 Jan 3, 2023
Solana NFT mint website + marketplace

Solana Candy Machine V2 + Candy Shop This repo allows you to sell NFTs through Candy Machine V2 and host your own secondary marketplace with Candy Sho

LIQNFT 91 Jan 2, 2023
🛠 Solana Web3 Tools - A set of tools to improve the user experience on Web3 Solana Frontends.

?? Solana Web3 Tools - A set of tools to improve the user experience on Web3 Solana Frontends.

Holaplex 30 May 21, 2022
solana-base-app is a base level, including most of the common features and wallet connectivity, try using `npx solana-base-app react my-app`

solana-base-app solana-base-app is for Solana beginners to get them up and running fast. To start run : run npx solana-base-app react my-app change th

UjjwalGupta49 33 Dec 27, 2022
This repo contains instructions on how to create your NFT in Solana(using Metaplex and Candy Machine) and mint it using your custom front-end Dapp

Solana-NFT minting Dapp Create your own NFT's on Solana, and mint them from your custom front-end Dapp. Tools used Metaplex -> Metaplex is the NFT sta

Udit Sankhadasariya 12 Nov 2, 2022