首页  >  文章  >  web前端  >  使用 Nextjs 构建中间件

使用 Nextjs 构建中间件

PHPz
PHPz原创
2024-08-13 07:00:021034浏览

Building a middleware with 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn