sdsdd

xxxxxx

sdsdd
/*
Visitors.ts
*/
import type { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const result = await fetch(
    `https://plausible.io/api/v1/stats/realtime/visitors?site_id=[SiteAdress]`,
    {
      method: 'GET',
      headers: {
        Authorization: `Bearer ${process.env.PLAUSIBLE_API_TOKEN}`
      }
    }
  );
  const data = await result.json();
  if (!result.ok) {
    return res
      .status(500)
      .json({ error: 'Error retrieving realtime visitors' });
  }
  res.setHeader(
    'Cache-Control',
    'public, s-maxage=60, stale-while-revalidate=60'
  );

  return res.status(200).json({ visitors: data });
}

Intro

If you want to show visitors on your site in real time and at the same time do not want to use GDPR and Cookie banners, Plausible is for you.

Usage

If you are using Vercel like me, you can add the env variable from the Vercel Environments Variables page.

/*
Visitors.tsx
*/
import { fetcher } from '@/lib/fetcher';
import useSWR from 'swr';

export function Visitors() {
  const { data: liveVisitors } = useSWR<any>(
    '/api/statistics/visitors',
    fetcher
  );
  return (
    <div className="col-span-4 h-32 justify-center text-center bg-gray-100 dark:bg-midnight rounded-lg p-6 flex flex-col items-center">
      <div className="flex items-center space-x-2">
        <h2 className="text-3xl font-bold m-0">
          {liveVisitors ? liveVisitors?.visitors : '--'} people
        </h2>
        <span className="flex h-3 w-3">
          <span className="relative inline-flex rounded-full h-3 w-3 bg-teal-500"></span>
          <span className="animate-ping absolute inline-flex h-3 w-3 rounded-full bg-teal-400 opacity-75"></span>
        </span>
      </div>
      <p className="text-base m-0">Visiting right now</p>
    </div>
  );
}

Then you can easily use it to configure whatever you need in your application. It's pretty easy to use and I think it works pretty well.