payloadcms / payload-admin-bar

An admin bar for React apps using Payload
MIT License
24 stars 4 forks source link

Fetch only when payload-token is set #2

Open Cuzart opened 1 year ago

Cuzart commented 1 year ago

This is not really an issue but a proposal for a performance improvement. The component is initially fetching "me" to detect if a user is logged in. For regular visitors this increases the initial load even though they are not editors. In my own project I used a wrapper for the AdminBar to check if the payload-token HttpOnly Cookies is set. If so I render the admin bar which fetches "me". I could open a PR with this approach applied if someone else finds this useful.

const hasHttpOnlyCookie = (key: string) => {
    document.cookie = key + "=anything;path=/;";
    return document.cookie.indexOf(key + "=") == -1;
  }

  useEffect(() => {
    const tokenExists = hasHttpOnlyCookie("payload-token");
    if (tokenExists) setShowAdminBar(true);
  }, []);
cbratschi commented 1 year ago

Code snippet for Next.js SSR:

import { cookies } from 'next/headers';

...

function MyComponent() {
    const cookieStore = cookies();

    if (!cookieStore.has('payload-token')) {
        return null:
    }

    ...
}

This completely removes the admin bar for non-Payload users.