在nextJS中为cookie创建HOC(高阶组件) [英] Creating a HOC (higher order component) for cookies in nextJS
问题描述
所以我要在nextJS应用程序中创建身份验证逻辑.我创建了/api/auth/login页面,在这里我处理请求,如果用户数据良好,我会使用JWT令牌创建一个httpOnly cookie并将一些数据返回到前端,该部分工作正常,但是我需要某种方式来保护某些页面,所以仅登录的用户可以访问他们,我为此创建HOC遇到了问题.我看到的最好的方法是使用getInitialProps,但是在NextJS网站上说我不应该再使用它,因此我认为可以使用getServerSideProps,但是它要么都不起作用,否则我可能做错了事.
So i'm creating authentication logic in my nextJS app. I created /api/auth/login page where i handle reqest and if user's data is good, im creating a httpOnly cookie with JWT token and returning some data to frontend, That part works fine but i need some way to protect some pages so only the logged users can acces them and i have problem with creating a HOC for that. The best way i saw is to use getInitialProps but on NextJS site it says that i shouldn't use it anymore so i thought abut using getServerSideProps but that dont work either or i'm propably doing something wrong.
这是我的HOC代码:(Cookie以"userToken"名称存储)
this is my HOC code: (cookie are stored under "userToken" name)
import React from 'react';
const jwt = require('jsonwebtoken');
const RequireAuthentication = (WrappedComponent) => {
return WrappedComponent;
};
export async function getServerSideProps({req,res}) {
const token = req.cookies.userToken || null;
// no token so i take user to login page
if (!token) {
res.statusCode = 302;
res.setHeader('Location', '/admin/login')
return {props: {}}
} else {
// we have token so i return nothing without changing location
return;
}
}
export default RequireAuthentication;
如果您还有其他关于如何使用cookie在nextJS中处理auth的想法,我将不胜感激,因为我是服务器端渲染React/auth的新手.
If you have any other ideas how to handle auth in nextJS with cookies i would be grateful for help because i'm new to the server side rendering react/auth
推荐答案
您应该将HOC逻辑与 getServerSideProps
分开.例如,您可以拥有一个HOC函数,该函数可以接受另一个函数(您的 getServerSideProps
),并且如果未设置 userToken
,则可以重定向到您的登录页面.
You should separate your HOC logic from getServerSideProps
. For instance, you could have a HOC function that would accept another function (your getServerSideProps
) and would redirect to your login page if the userToken
wasn't set.
export function requireAuthentication(gssp) {
return async (context) => {
const { req, res } = context;
const token = getUserToken(req.headers.cookie) // Add logic to extract token from `req.headers.cookie`
if (!token) {
// Redirect to login page
res.statusCode = 302;
res.setHeader('Location', '/admin/login');
return;
}
return await gssp(context); // Continue on to call `getServerSideProps` logic
}
}
然后,您可以通过包装 getServerSideProps
函数在页面中使用它.
You would then use it in your page by wrapping the getServerSideProps
function.
// pages/index.js (or some other page)
export const getServerSideProps = requireAuthentication(context => {
// Your normal `getServerSideProps` code here
})
这篇关于在nextJS中为cookie创建HOC(高阶组件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!