1.1.1 • Published 2 years ago

next-auth-swr v1.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

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

OptionTypeDescriptionDefault
requiredbooleanStandard next-auth option (See more)false
onUnauthenticated() => voidStandard next-auth option (See more)undefined
configSWRConfigurationStandard swr configuration (See more)undefined

SessionProvider

Options

OptionTypeDescriptionDefault
sessionSessionThe default session (useSession fallback data)undefined
configSWRConfigurationStandard swr configuration (See more)undefined

License

MIT

1.1.1

2 years ago

1.1.0

2 years ago

1.0.0

2 years ago

0.0.1

2 years ago