在这篇短文中,我将写关于如何使用 nextjs 构建中间件。
我最近使用 nextjs 构建了一个完整的后端服务,我对 nextjs 的进步感到非常震惊。
您需要具备 javascript 和 nodejs 的基本知识才能阅读本文。
要开始,您需要
1.使用以下命令从终端创建一个 nextjs 项目
npx create-next-app@latest
运行此命令后,您将收到一些配置项目的提示,请执行此操作。
创建项目后,
2.通过在终端中运行 npm install 安装必要的依赖项
我们将只安装一个用于身份验证的包库,即 jose,替代方案可能是 jsonwebtoken,但是 nextjs 中间件在浏览器上运行,因此边缘运行时不会实现一堆 node.js api
3.使用下面的命令以开发模式启动您的项目
npm run dev
4.创建一个 middleware.js 文件
在项目的根目录创建一个 middleware.js 文件,如果您使用的是 /src 目录,请在 /src 目录中创建该文件
5。从文件中导出中间件函数
// /middleware.js export const middleware = async (req) => { try { } catch(error){ console.log(error) } }
6。从请求标头中提取令牌
// /middleware.js import { nextresponse } from 'next/server' export const middleware = async (req) => { try { const header = req.headers.get('authorization'); if(!header) return nextresponse.json({ status:'error' statuscode: 400, message:'unauthenticated' }) const token = header.split(" ")[1]; if(!token) return nextresponse.json({ status:'error' statuscode: 401, message:'you are not logged in' }) } catch(error){ console.log(error) } }
7.使用 jose 验证令牌
// /middleware.js import { nextresponse } from 'next/server'; import * as jose from 'jose' export const middleware = async (req) => { try { const header = req.headers.get('authorization'); if(!header) return nextresponse.json({ status:'error' statuscode: 400, message:'unauthenticated' }) const token = header.split(" ")[1]; if(!token) return nextresponse.json({ status:'error' statuscode: 401, message:'you are not logged in' }) const { payload } = await jose.jwtverify( token, new textencoder().encode(process.env.next_public_jwt_key) ); // your encoded data will be inside the payload object. } catch(error){ console.log(error) } }
8.从已验证的令牌中提取数据并将其设置在请求标头中
// /middleware.js import { nextresponse } from 'next/server'; import * as jose from 'jose' export const middleware = async (req) => { try { const header = req.headers.get('authorization'); if(!header) return nextresponse.json({ status:'error' statuscode: 400, message:'unauthenticated' }) const token = header.split(" ")[1]; if(!token) return nextresponse.json({ status:'error' statuscode: 401, message:'you are not logged in' }) const { payload } = await jose.jwtverify( token, new textencoder().encode(process.env.next_public_jwt_key) ); const requestheaders = new headers(req.headers) requestheaders.set('user', payload.id) } catch(error){ console.log(error) } }
9.调用 next() 函数并传递更新后的请求头
// /middleware.js import { nextresponse } from 'next/server'; import * as jose from 'jose' export const middleware = async (req) => { try { const header = req.headers.get('authorization'); if(!header) return nextresponse.json({ status:'error' statuscode: 400, message:'unauthenticated' }) const token = header.split(" ")[1]; if(!token) return nextresponse.json({ status:'error' statuscode: 401, message:'you are not logged in' }) const { payload } = await jose.jwtverify( token, new textencoder().encode(process.env.next_public_jwt_key) ); const requestheaders = new headers(req.headers) requestheaders.set('user', payload.id) return nextresponse.next({ request: { headers: requestheaders } }) } catch(error){ console.log(error) } }
10。最后,您需要从中间件文件中导出一个配置对象,其中包含有关您要保护的路由的配置。
// /middleware.js import { NextResponse } from 'next/server'; import * as jose from 'jose' export const config = { matcher:[ // contain list of routes you want to protect, e.g /api/users/:path* ] } export const middleware = async (req) => { try { const header = req.headers.get('authorization'); if(!header) return NextResponse.json({ status:'error' statusCode: 400, message:'unauthenticated' }) const token = header.split(" ")[1]; if(!token) return NextResponse.json({ status:'error' statusCode: 401, message:'You are not logged in' }) const { payload } = await jose.jwtVerify( token, new TextEncoder().encode(process.env.NEXT_PUBLIC_JWT_KEY) ); const requestHeaders = new Headers(req.headers) requestHeaders.set('user', payload.id) return NextResponse.next({ request: { headers: requestHeaders } }) } catch(error){ console.log(error) } }
我希望这 10 个步骤对您有所帮助,请在评论部分告诉我您对此方法的看法,如果有更好的方法来实现这一点,请随时分享。
谢谢你。