Skip to content

jozefhruska/next-auth-swr

Repository files navigation

NextAuth.js SWR Client

An SWR-powered alternative to NextAuth.js built-in client

npm version badge package size badge license badge

Overview

Inspired by @next-auth/react-query, next-auth-swr is an alternative client for next-auth powered by SWR. It works as a drop-in replacement for the standard useSession API and offers all the features of SWR we love so much ❤️️.

Getting Started

import { useSession } from 'next-auth-swr';

const Profile: React.FC = () => {
  const {
    data: session,
    error,
    isValidating,
    mutate,
  } = useSession({
    required: true,
    onUnauthenticated: () => {
      console.log('Who are you?');
    },
    config: {
      refreshInterval: 20000,
      dedupingInterval: 5000,
      // Other standard SWR options...
    },
  });

  if (error) return <div>Oops, something went wrong!</div>;

  if (!session && isValidating) return <div>Loading...</div>;

  if (!session) return <div>Hello, stranger!</div>;

  return <div>Hello, {session.user.name}!</div>;
};

Warning
Ensure you import useSession from next-auth-swr and not the original next-auth package.

Default session data

To configure the default session or SWR configuration globally, you can use the SessionProvider. All useSession hooks consuming the global context will use the default session as the fallback data.

import { AppProps } from "next/app";
import { SWRConfig } from "swr";

const MyApp = ({ Component, pageProps }: AppProps) => (
  <SessionProvider
    session={pageProps.session}
    config={{
      refreshInterval: 30000,
      refreshWhenHidden: false,
    }}
  >
    <Component {...pageProps} />
  </SessionProvider>
);

export default MyApp;

Note
You can also use the standard SWRConfig, but remember this will affect all SWR hooks, not only the useSession hook.

API Reference

useSession

useSession(options?: UseSessionOptions): SWRResponse<Session | null>

Options

Option Type Description Default
required boolean Standard next-auth option (See more) false
onUnauthenticated () => void Standard next-auth option (See more) undefined
config SWRConfiguration Standard swr configuration (See more) undefined

SessionProvider

Options

Option Type Description Default
session Session The default session (useSession fallback data) undefined
config SWRConfiguration Standard swr configuration (See more) undefined

License

MIT