首頁  >  文章  >  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