【问题标题】:Passing variables from middleware to page in Next.js 12 new middleware apiNext.js 12 新的中间件 api 将变量从中间件传递到页面
【发布时间】:2021-12-13 15:58:44
【问题描述】:

问题的背景

Vercel 最近发布了他们对 Next.js 的最大更新。 Next.js blog。 他们引入了很多新功能,但我最喜欢的是Middleware

"使您能够使用代码而不是配置。这为您提供了完整的 Next.js 的灵活性,因为您可以在请求之前运行代码 完全的。根据用户传入的请求,可以修改 通过重写、重定向、添加标头甚至流式传输来响应 HTML。”

问题

本题使用以下结构。

- /pages
    index.js
    signin.js
    - /app
      _middleware.js # Will run before everything inside /app folder
      index.js

这里的两个重要文件是/app/_middleware.js/app/index.js

// /app/_middleware.js

import { NextResponse } from 'next/server';

export function middleware(req, event) {
  const res = { isSignedIn: true, session: { firstName: 'something', lastName: 'else' } }; // This "simulates" a response from an auth provider
  if (res.isSignedIn) {

    // Continue to /app/index.js
    return NextResponse.next();
  } else {

    // Redirect user
    return NextResponse.redirect('/signin');
  }
}
// /app/index.js

export default function Home() {
  return (
    <div>
      <h1>Authenticated!</h1>
      
      // session.firstName needs to be passed to this file from middleware
      <p>Hello, { session.firstName }</p>
    </div>
  );
}

在此示例中,/app/index.js 需要访问 res.session JSON 数据。是否可以在NextResponse.next() 函数中传递它,还是需要做其他事情?

快递可以res.locals.session = res.session

【问题讨论】:

  • 您需要在该页面中使用getServerSideProps 才能访问res.session。您不能直接从组件本身访问它。

标签: next.js


【解决方案1】:

According to the examples(特别是/pages/_middleware.ts/lib/auth.ts)看起来这样做的规范方法是通过 cookie 设置您的身份验证。

在你的中间件函数中,它看起来像:

// /app/_middleware.js

import { NextResponse } from 'next/server';

export function middleware(req, event) {
  const res = { isSignedIn: true, session: { firstName: 'something', lastName: 'else' } }; // This "simulates" a response from an auth provider
  if (res.isSignedIn) {

    // Continue to /app/index.js
    return NextResponse.next().cookie("cookie_key", "cookie_value"); // <--- SET COOKIE
  } else {

    // Redirect user
    return NextResponse.redirect('/signin');
  }
}

【讨论】:

  • 是的,但据我所知,您不应将用户信息存储在 cookie 中。它可以很容易地被最终用户操纵。我想到的一个更好的解决方案是使用 reacts createContext 创建一个商店
  • 这是一个简单的例子,如果你正在实现一个基于 cookie 的方法,你可能想要加密 cookie 本身,或者在 cookie 中存储一个 JWE。
  • 非常感谢您帮助我尝试找到解决方法。但它不应该是执行此操作的默认方式吗?
  • 应该吗?当然,这是一个很棒的功能,但是有人问了this same question in the RFC,但没有得到回答,这让我相信目前不可能。我的假设是他们为 Next12/Nextconf 设置了 MVP。希望这个功能在路线图上(或者其他人可以证明我错了,这是可能的)。
猜你喜欢
  • 1970-01-01
  • 2016-03-25
  • 2021-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-20
相关资源
最近更新 更多