首页 > web前端 > js教程 > 正文

使用 Nextjs 构建中间件

WBOY
发布: 2024-08-13 16:45:40
转载
702人浏览过

使用 nextjs 构建中间件

在这篇短文中,我将写关于如何使用 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 个步骤对您有所帮助,请在评论部分告诉我您对此方法的看法,如果有更好的方法来实现这一点,请随时分享。

谢谢你。

以上就是使用 Nextjs 构建中间件的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号