An SWR-powered alternative to NextAuth.js built-in client
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 ❤️️.
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 importuseSession
fromnext-auth-swr
and not the originalnext-auth
package.
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 standardSWRConfig
, but remember this will affect all SWR hooks, not only theuseSession
hook.
useSession(options?: UseSessionOptions): SWRResponse<Session | null>
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 |
Option | Type | Description | Default |
---|---|---|---|
session |
Session |
The default session (useSession fallback data) |
undefined |
config |
SWRConfiguration |
Standard swr configuration (See more) |
undefined |
MIT