React Query wrapper for NextAuth.js session management

Related tags

React react-query
Overview

Next Auth logo    plus sign    React Query logo

NextAuth.js React-Query Client

@next-auth/react-query

React Query wrapper for NextAuth.js session management.

Downloads Github Stars Github Stable Release

Overview

This is an alternative client for next-auth based upon react-query. It can replace the built-in session management on the client-side by taking advantage of react-query's built-in caching, auto refetching, etc.

Getting Started

npm install --save @next-auth/react-query

You can then import useSession from this package, instead of the core next-auth package. More usage details can be found below.

API Reference

useSession

useSession(params: UseSessionParams) : UseSessionResult

React Query wrapper to retrieve Session. Replaces useSession and Provider from next-auth/client in codebases where you already use react-query.

UseSessionParams

import { useSession } from "@next-auth/react-query"
...
const [session, loading] = useSession({
  required: true,
  redirectTo: "/auth/sign-in?error=InvalidSession",
  queryConfig: {
    staleTime: 60 * 60 * 3, // 3 hours
    refetchInterval: 60 * 5 // 5 minutes 
  }
})
...
Parameter Type Description Default
required boolean If true, will redirect when no session available false
redrectTo string When required: true, this is where the user will be redirected "/api/auth/session"
queryConfig UseQueryOptions See React Query's useQuery Options {}

TIP: staleTime and refetchInterval respectively match clientMaxAge and keepAlive from the Original API.

UseSessionResult

import { useSession } from "@next-auth/react-query"
...
const [session, loading] = useSession()
...

The shape of what useSession returns matches the Original API.

Acknowledgements

Based on this discussion between @kripod and @balazsorban44

Contributing

We're open to all community contributions! If you'd like to contribute in any way, please first read our Contributing Guide.

License

ISC

Comments
  • possible add nextauthjs / react-query in existing react-query ? -  No QueryClient set, use QueryClientProvider to set one

    possible add nextauthjs / react-query in existing react-query ? - No QueryClient set, use QueryClientProvider to set one

    I am sory maybe sounds like the questions. I've existing next auth, and react-query setup. then i adding /nextauthjs/react-query lib with

    import { useSession } from "@next-auth/react-query"
    
    const [session, loading] = useSession({
      required: true,
      redirectTo: "/auth/sign-in?error=InvalidSession",
      queryConfig: {
        staleTime: 60 * 60 * 3, // 3 hours
        refetchInterval: 60 * 5 // 5 minutes 
      }
    })
    

    and i got some error No QueryClient set, use QueryClientProvider to set one

    any or something wrong or need additional setup on my code?

    stale 
    opened by isggwp 25
  • Support for Next.js 12 and NextAuth v4

    Support for Next.js 12 and NextAuth v4

    I'm currently trying to use this library using the following versions of Nextjs and NextAuth, but having the below error:

    dependencies:

    next: 12.0.3
    next-auth: 4.0.0-beta.6
    node: v14.18.1
    typescript: 4.4.4
    

    error:

    > Build error occurred
    Error: Dynamic require of "react" is not supported
        at xe (file:///myproject/node_modules/@next-auth/react-query/dist/index.mjs:1:294)
        at file:///myproject/node_modules/@next-auth/react-query/dist/index.mjs:1:39268
        at file:///myproject/node_modules/@next-auth/react-query/dist/index.mjs:1:373
        at file:///myproject/node_modules/@next-auth/react-query/dist/index.mjs:4:497
        at file:///myproject/node_modules/@next-auth/react-query/dist/index.mjs:1:373
        at file:///myproject/node_modules/@next-auth/react-query/dist/index.mjs:4:14209
        at ModuleJob.run (internal/modules/esm/module_job.js:183:25)
        at async Loader.import (internal/modules/esm/loader.js:178:24) {
      type: 'Error'
    }
    
    opened by ffleandro 6
  • npm install fails with next 11.1

    npm install fails with next 11.1

    Not sure how I broke it...

    $ npm install --save @next-auth/react-query
    
    npm ERR! code ERESOLVE
    npm ERR! ERESOLVE unable to resolve dependency tree
    npm ERR! While resolving: undefined@undefined
    npm ERR! Found: [email protected]
    npm ERR! node_modules/next
    npm ERR!   next@"^11.0.0" from the root project
    npm ERR! Could not resolve dependency:
    npm ERR! peer next@"^10.0.3" from @next-auth/[email protected]
    npm ERR! node_modules/@next-auth/react-query
    npm ERR!   @next-auth/react-query@"*" from the root project
    ...
    

    next 11.1 next-auth 3.29.0 react-query 3.21.1 typescript 4.2.4

    bug good first issue 
    opened by jacobdubail 3
  • Potential Bug: SyntaxError: Cannot use import statement outside a module

    Potential Bug: SyntaxError: Cannot use import statement outside a module

    Hi,

    When I tried to use @next-auth/react-query, it showed following errors. Do you know what should I do for it? It seems that the index.js is using import syntax which is not allowed.

    import { useQuery } from "react-query"
    ^^^^^^
    SyntaxError: Cannot use import statement outside a module
        at compileFunction (<anonymous>)
        at Module._compile (internal/modules/cjs/loader.js:891:18)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
        at Module.load (internal/modules/cjs/loader.js:811:32)
        at Function.Module._load (internal/modules/cjs/loader.js:723:14)
        at Module.require (internal/modules/cjs/loader.js:848:19)
        at require (internal/modules/cjs/helpers.js:74:18)
        at Object.@next-auth/react-query (/home/kos/git/opensource/onr-react-ui/examples/next-starter/.next/server/pages/_app.js:2703:18)
        at __webpack_require__ (/home/kos/git/opensource/onr-react-ui/examples/next-starter/.next/server/webpack-runtime.js:33:43)
        at eval (webpack-internal:///./src/app/components/PageContainer.tsx:7:80)
    
    stale 
    opened by koshuang 2
  • Default queryConfig to empty object

    Default queryConfig to empty object

    Reasoning 💡

    Tiny change! I'd like to see the queryConfig parameter defaulted to an empty object so that if it isn't specified, we don't see an error calling useSession.

    Checklist 🧢

    • [x] Documentation
    • [ ] Tests
    • [x] Ready to be merged

    I haven't run tests to check this yet. Documentation already talks about {} as the default.

    opened by jakeorr 1
  • fix: type definitions not published in npm package

    fix: type definitions not published in npm package

    package.files[] used to include a wrong path to the type definitions file (index.d.js instead of index.d.ts), and as such, they didn't get published into the npm package, leaving consumers of this package without proper type definitions.

    Screenshot 2021-06-11 210908

    This PR fixes that by changing the path in package.files[] from index.d.js to index.d.ts

    How to validate

    Run npm publish --dry-run on master:

    $ npm publish --dry-run
    npm notice 
    npm notice 📦  @next-auth/[email protected]
    npm notice === Tarball Contents === 
    npm notice 3.7kB  README.md     
    npm notice 55.1kB dist/index.js 
    npm notice 55.0kB dist/index.mjs
    npm notice 730B   index.js      
    npm notice 1.5kB  package.json  
    npm notice === Tarball Details === 
    npm notice name:          @next-auth/react-query                  
    npm notice version:       0.0.8                                   
    npm notice filename:      @next-auth/react-query-0.0.8.tgz        
    npm notice package size:  38.3 kB                                 
    npm notice unpacked size: 116.1 kB                                
    npm notice shasum:        ebe3358bcc79a8c479861fc16ef51d9b425e3d16
    npm notice integrity:     sha512-DWbWDDNRCa+eU[...]19OdZO1F0LA6w==
    npm notice total files:   5                                       
    npm notice 
    + @next-auth/[email protected]
    

    See how it doesn't contain index.d.ts.

    Now, run the same npm publish --dry-run on this branch:

    $ npm publish --dry-run
    npm notice 
    npm notice 📦  @next-auth/[email protected]
    npm notice === Tarball Contents === 
    npm notice 3.7kB  README.md     
    npm notice 55.1kB dist/index.js 
    npm notice 55.0kB dist/index.mjs
    npm notice 912B   index.d.ts    
    npm notice 730B   index.js      
    npm notice 1.5kB  package.json  
    npm notice === Tarball Details === 
    npm notice name:          @next-auth/react-query                  
    npm notice version:       0.0.8                                   
    npm notice filename:      @next-auth/react-query-0.0.8.tgz        
    npm notice package size:  38.7 kB                                 
    npm notice unpacked size: 117.0 kB                                
    npm notice shasum:        60503efa2afc5505a848477e2f138a3e54f1e619
    npm notice integrity:     sha512-2WVGrFeX8g2lw[...]DOOhcZ2ODZDEg==
    npm notice total files:   6                                       
    npm notice 
    + @next-auth/[email protected]
    

    It now contains index.d.ts.

    Checklist 🧢

    ~[ ] Documentation~ ~[ ] Tests~

    • [x] Ready to be merged
    opened by wolfika 1
  • feat: esbuild to generate esm+cjs output

    feat: esbuild to generate esm+cjs output

    Create both esm and cjs output files to support next.js correctly

    Fixes #4

    Notes:

    • main + modules in package.json strategy: https://2ality.com/2019/10/hybrid-npm-packages.html#option-1-(experimental%2C-needs-conditional-exports)%3A-esm-and-commonjs-are-both-bare-imports
    • esbuild docs: https://esbuild.github.io/getting-started/
    opened by ndom91 0
  • docs: update README.md

    docs: update README.md

    Updated README.md to more match the rest of the packages we have.

    Also added the basic PR template, stale settings and super basic CI lint job to bring this repo up to speed with the rest of ours :+1:

    EDIT: Oops, package-lockv2 (npm7) issue again.. If its a problem, please push your npm6 package-lock over this one before merging :+1:

    opened by ndom91 0
  • Error: Package path . is not exported from package

    Error: Package path . is not exported from package

    Please see the image or text below for further details:

    ./src/hooks/mutations/useUpdateUser.ts:1:0
    Module not found: Package path . is not exported from package /Users/kripod/Development/folio/node_modules/@next-auth/react-query (see exports field in /Users/kripod/Development/folio/node_modules/@next-auth/react-query/package.json)
    > 1 | import { useSession } from "@next-auth/react-query";
      2 | import type { Session } from "next-auth";
      3 | import { useMutation, useQueryClient } from "react-query";
      4 | 
    
    opened by kripod 0
Owner
NextAuth.js
Authentication for Next.js
NextAuth.js
Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.

Recoil · Recoil is an experimental set of utilities for state management with React. Please see the website: https://recoiljs.org Installation The Rec

Facebook Experimental 18.2k Jan 8, 2023
Source code for the deprecated expo-google-app-auth package. Deprecated in favor of expo-auth-session.

expo-google-app-auth Source code for the deprecated expo-google-app-auth package. Expo Google App Auth API wrapped the deprecated expo-app-auth packag

Expo 4 Nov 2, 2022
Mirrors the functionality of Apollo client's useQuery hook, but with a "query" being any async function rather than GQL statement.

useAsyncQuery Mirrors the functionality of Apollo client's useQuery hook, but with a "query" being any async function rather than GQL statement. Usage

Alasdair McLeay 7 Nov 16, 2022
🐻 Bear necessities for state management in React

A small, fast and scaleable bearbones state-management solution. Has a comfy api based on hooks, isn't boilerplatey or opinionated, but still just eno

Poimandres 25.5k Jan 9, 2023
🏁 High performance subscription-based form state management for React

You build great forms, but do you know HOW users use your forms? Find out with Form Nerd! Professional analytics from the creator of React Final Form.

Final Form 7.2k Jan 7, 2023
A state management library for React, heavily inspired by vuex

Vuex - But for React! ⚛ If you know vuex, you know it's as close as we get to a perfect state management library. What if we could do this in the reac

Dana Janoskova 103 Sep 8, 2022
Twitter-Clone-Nextjs - Twitter Clone Built With React JS, Next JS, Recoil for State Management and Firebase as Backend

Twitter Clone This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn de

Basudev 0 Feb 7, 2022
React friendly API wrapper around MapboxGL JS

react-map-gl | Docs react-map-gl is a suite of React components designed to provide a React API for Mapbox GL JS-compatible libraries. More informatio

Vis.gl 6.9k Dec 31, 2022
🔮 tiny robust state management

?? snapstate tiny robust state management ?? npm install @chasemoskal/snapstate ??️ watch for changes to properties ??️ track only the properties you

Chase Moskal 5 Dec 23, 2022
A fleet management Application built with the service providers and user in mind

A fleet management Application built with the service providers and user in mind. A multi faceted Admin and consumer console application for mobile.

Pranav Murali 4 Feb 27, 2022
A tiny package for JavaScript Web App's state management based on RxJS & Immer

A tiny package for JavaScript Web App's state management based on RxJS & Immer

Xiao Junjiang 12 Oct 19, 2022
Tiny and powerful state management library.

BitAboutState Tiny and powerful React state management library. 100% Idiomatic React. Install npm install --save @bit-about/state Features 100% Idioma

null 53 Nov 5, 2022
Learning how to use redux - a state management library

Redux Learning how to use redux - a state management library What is Redux? Redux is a state management library for JS apps. It centralizes applicatio

Melvin Ng 3 Jul 18, 2022
React Starter Kit — isomorphic web app boilerplate (Node.js, Express, GraphQL, React.js, Babel, PostCSS, Webpack, Browsersync)

React Starter Kit — "isomorphic" web app boilerplate React Starter Kit is an opinionated boilerplate for web development built on top of Node.js, Expr

Kriasoft 21.7k Dec 30, 2022
📋 React Hooks for forms validation (Web + React Native)

English | 繁中 | 简中 | 日本語 | 한국어 | Français | Italiano | Português | Español | Русский | Deutsch | Türkçe Features Built with performance and DX in mind

React Hook Form 32.4k Dec 29, 2022
:black_medium_small_square:React Move | Beautiful, data-driven animations for React

React-Move Beautiful, data-driven animations for React. Just 3.5kb (gzipped)! Documentation and Examples Features Animate HTML, SVG & React-Native Fin

Steve Hall 6.5k Jan 1, 2023
React features to enhance using Rollbar.js in React Applications

Rollbar React SDK React features to enhance using Rollbar.js in React Applications. This SDK provides a wrapper around the base Rollbar.js SDK in orde

Rollbar 39 Jan 3, 2023
🎉 toastify-react-native allows you to add notifications to your react-native app (ios, android) with ease. No more nonsense!

toastify-react-native ?? toastify-react-native allows you to add notifications to your react-native app (ios, android) with ease. No more nonsense! De

Zahid Ali 29 Oct 11, 2022
Soft UI Dashboard React - Free Dashboard using React and Material UI

Soft UI Dashboard React Start your Development with an Innovative Admin Template for Material-UI and React. If you like the look & feel of the hottest

Creative Tim 182 Dec 28, 2022