Next.js & RTK Query - 检查每个页面上的用户身份验证



我正在使用RTK查询Next.js,我想检查用户是否登录或不改变标题布局和标题文本和潜在的其他东西,我应该如何做到这一点,而不使用getInitialProps?

Next.js不建议使用getInitialProps,因为它对性能不理想,但是,推荐的方法是getServerSideProps,不能在_app.tsx级别上工作。

我正在考虑使用NextAuth,但我不知道如何做到这一点,而使用RTK Query,我找不到任何例子。

如果有人能指出我在正确的方向或最好的工作流程认证用户在Next.js的每一页与RTK查询,这将是伟大的。

为了获得用户是否经过身份验证,用户向端点发出请求,在next.js中,您可以在api目录中定义它,在该目录中构建rest-api代码。

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
export const authApi = createApi({
reducerPath: "authApi",
baseQuery: fetchBaseQuery({
baseUrl: "http://localhost:300/",
}),
// builder is an object that has mutation and query
endpoints: (builder) => {
console.log("builder", builder);
return {
// we are making post that is wht it is mutation. otherwise it would be query
fetchUser: builder.query({
query:()=> "/api/user"
}),
....
export const {usefetchUserQuery,otherQueriesOrMutations} = authenticationApi;

然后注册到store.js

export const store = configureStore({
reducer: {
// assuming you already set the slices of the app
auth: authReducer,
[authenticationApi.reducerPath]: contactsApi.reducer,
},
// userAPI is the middleware that we hook in store which enables caching, invalidation, polling, and other useful features of `rtk-query`
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(authenticationApi.middleware),
});

api/user中,根据您的身份验证逻辑,返回是否为用户。如果你使用next-auth

import { getSession } from "next-auth/client"
export default async (req, res) => {
const session = await getSession({ req })
... 
res.sned(true)
}

我假设您已经设置了身份验证逻辑。或者您可能有基于令牌的身份验证

const token = req ? req.cookies?.token : null;
res.send(token)

基本上这将是你检查用户的中心点。

由于头组件需要用户,因此可以在Header组件的useEffect中调度一个操作来检查用户是否经过身份验证。或者你可以设置SessionProvider,这样你可以在头组件

useSession钩子
// signIn for signing click, signOut is for signing out click
import { signIn, signOut, useSession } from "next-auth/react"
const { data: session, status } = useSession()
const loading = status === 'loading'

如果你想从服务器端道具中获取用户,你必须将用户道具钻取到header组件中。根据您如何设置redux应用程序(是否使用next-redux-wrapper),分派操作将有所不同

最新更新