如何在Next.js中使用getStaticProps或getServerSideProps处理基于动态授权的内容?

huangapple go评论73阅读模式
英文:

How to handle dynamic authorization-based content in Next.js with getStaticProps or getServerSideProps?

问题

我正在构建一个Next.js应用程序,需要根据用户的授权状态获取并显示内容。最初我使用getStaticProps在构建时获取和缓存内容。然而,我意识到缓存的内容会提供给所有用户,不考虑他们的授权状态。这可能存在潜在的安全风险,因为未经授权的用户可能会看到敏感内容。

为解决这个问题,我考虑改用getServerSideProps,因为它在每个请求时生成内容,允许我动态检查授权状态并提供适当的内容。然而,我不确定如何最好地处理这种情况。

这是我尝试使用getServerSideProps的示例:

import { useRouter } from 'next/router';

export async function getServerSideProps(context) {
  const { authorization } = context.req.headers;
  const { id } = context.query;

  // 检查授权值
  if (authorization === 'valid_token') {
    // 根据ID获取经授权的内容
    const authorizedData = await fetch(`https://api.example.com/authorized/${id}`);
    const authorizedContent = await authorizedData.json();

    return {
      props: {
        content: authorizedContent,
      },
    };
  } else {
    // 根据ID获取未经授权的内容
    const unauthorizedData = await fetch(`https://api.example.com/unauthorized/${id}`);
    const unauthorizedContent = await unauthorizedData.json();

    return {
      props: {
        content: unauthorizedContent,
      },
    };
  }
}

function MyPage({ content }) {
  // 根据授权状态呈现内容
  return (
    <div>
      <h1>My Page</h1>
      <p>{content.title}</p>
      <p>{content.description}</p>
    </div>
  );
}

export default MyPage;

我会感激以下方面的任何指导:

  1. 在Next.js中处理基于动态授权的内容,使用getServerSideProps是正确的方法吗?

  2. 在这种情况下,使用getServerSideProps而不是getStaticProps是否存在潜在的缺点或性能影响?

  3. 在Next.js中处理基于动态授权的内容,是否有更高效或替代的方法?
    感谢您提供的任何帮助或建议。谢谢!

英文:

I am building a Next.js application where I need to fetch and display content based on the user's authorization status. I initially used getStaticProps to fetch and cache the content at build time. However, I realized that the cached content is served to all users, regardless of their authorization status. This poses a potential security risk as unauthorized users might see sensitive content.

To address this issue, I considered using getServerSideProps instead, as it generates the content on each request, allowing me to check the authorization status dynamically and serve the appropriate content. However, I am unsure about the best approach to handle this situation.

Here is an example of what I have tried using getServerSideProps:

import { useRouter } from &#39;next/router&#39;;

export async function getServerSideProps(context) {
  const { authorization } = context.req.headers;
  const { id } = context.query;

  // Check the authorization value
  if (authorization === &#39;valid_token&#39;) {
    // Fetch authorized content based on the ID
    const authorizedData = await fetch(`https://api.example.com/authorized/${id}`);
    const authorizedContent = await authorizedData.json();

    return {
      props: {
        content: authorizedContent,
      },
    };
  } else {
    // Fetch unauthorized content based on the ID
    const unauthorizedData = await fetch(`https://api.example.com/unauthorized/${id}`);
    const unauthorizedContent = await unauthorizedData.json();

    return {
      props: {
        content: unauthorizedContent,
      },
    };
  }
}

function MyPage({ content }) {
  // Render the content based on the authorization status
  return (
    &lt;div&gt;
      &lt;h1&gt;My Page&lt;/h1&gt;
      &lt;p&gt;{content.title}&lt;/p&gt;
      &lt;p&gt;{content.description}&lt;/p&gt;
    &lt;/div&gt;
  );
}

export default MyPage;

I would appreciate any guidance on the following points:

  1. Is using getServerSideProps the correct approach to handle dynamic authorization-based content in Next.js?

  2. Are there any potential drawbacks or performance implications of using getServerSideProps instead of getStaticProps in this scenario?

  3. Is there a more efficient or alternative way to handle dynamic authorization-based content in Next.js?
    Any help or suggestions would be greatly appreciated. Thank you!

答案1

得分: 1

正如你已经发现的那样,getStaticProps 不适用于处理动态内容或依赖于 cookies 或 headers 的内容,因为相关页面是在构建时生成的,不会在每个请求上渲染。

使用 SSR 处理动态内容是正确的方法吗?

绝对的,如果可能的话,将授权保留在服务器上,这确保了令牌和密钥不会泄漏给客户端。一般来说,当数据无法在用户请求发生之前静态生成,并且同时需要提供给搜索引擎时,特别推荐使用这种技术。

使用 SSR 会有潜在的缺点或性能影响吗?

可以这样想,只要数据没有被获取,页面就无法显示,用户将看到一个空白屏幕。在使用 SSR 时,非常重要的是尽可能地缓存内容,并确保你请求的任何外部 API 足够快以在生产环境中使用。

请注意,不管使用的渲染方法如何,共享的捆绑大小和首次加载的 JavaScript 代码将在性能方面起到重要作用。首次加载的 JavaScript 捆绑包括应用程序页面在初始加载时共享或使用的所有代码。

在 Next.js 中处理动态内容是否有更高效或替代的方法?

使用页面目录时,没有

但应用程序目录支持即时加载UI,基本上是在导航时立即显示的后备UI。你可以预渲染加载指示器,例如骨架和旋转器,或未来屏幕的一个小但有意义的部分,例如封面照片、标题等。这有助于用户理解应用程序正在响应,并提供更好的用户体验。

英文:

As you have already discovered for your self, getStaticProps is not the way to go when working with dynamic content or content that relies on cookies or headers as related pages are generated at build time and do not render on each request.


Is using SSR the correct approach to handle dynamic content?

Definitely, if possible keep your authorization on the server only, this ensures that your tokens and secrets never get leaked to the client. Generally speaking this technique is especially recommended when the data cannot be statically generated before a user request takes place, and at the same time needs to be available to search engines.

Are there any potential drawbacks or performance implications of using SSR?

Think of it this way, as long as your data has not been fetched the page can not be displayed and the user will see a blank screen. When using SSR it is really important to cache content whenever possible and ensure that any external API's you are requesting are fast enough to be used in production.

Note that your shared bundle size and First Load JS will play a big role in performance, no matter the rendering method used. The First Load JS bundle is all the code shared or used by the app pages at initial load.

Is there a more efficient or alternative way to handle dynamic content in Next.js?

Using the pages directory there is not no.

But the app directory supports instant loading UI's, basically fallback UI that is shown immediately upon navigation. You can pre-render loading indicators such as skeletons and spinners, or a small but meaningful part of future screens such as a cover photo, title, etc. This helps users understand the app is responding and provides a better user experience.

huangapple
  • 本文由 发表于 2023年7月3日 20:57:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76604960.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定