next.js 如何在一个NextPage页面中运行getServerSideProps?

kjthegm6  于 2022-11-05  发布在  其他
关注(0)|答案(1)|浏览(99)

这是我想要复制的页面类型(代码来自https://github.com/dabit3/nextjs-lit-token-gating/blob/main/pages/protected.js):

import Cookies from 'cookies'
import LitJsSdk from 'lit-js-sdk'

export default function Protected(props) {
  if (!props.authorized) {
    return (
      <h2>Unauthorized</h2>
    )
  }
  return (
    <div>
      <h2>Hello world</h2>
    </div>
  )
}

export async function getServerSideProps({ req, res, query }) {
  const { id } = query
  const cookies = new Cookies(req, res)
  const jwt = cookies.get('lit-auth')
  if (!jwt) {
    return {
      props: {
        authorized: false
      },
    }
  }

  const { verified, payload } = LitJsSdk.verifyJwt({ jwt })

  if (
    payload.baseUrl !== "http://localhost:3000"
    || payload.path !== '/protected'
    || payload.extraData !== id
  ) {
    return {
      props: {
        authorized: false
      },
    }
  }
  return {
    props: {
      authorized: verified ? true : false
    },
  }
}

但我已经习惯了这样制作next.js页面:
“受保护的.tsx”

import type { NextPage } from 'next'
import { useState } from 'react'
import styles from '../styles/Home.module.css'

const Protected: NextPage = (props: any) => {
  console.log("protected view pre run");
  console.log(props.authorized);
  if (!props.authorized) {
    return (
      <h2>Unauthorized</h2>
    )
  } else {
  return (
    <div className="hero min-h-screen bg-base-200">
      <div className="hero-content text-center">
        <div className="max-w-md">
          <h1 className="text-5xl font-bold">This is the Secret Gate</h1>
          <p className="py-6">Tell no one</p>
        </div>
      </div>
    </div>
  )}
}

export default Protected

我使用的是typescript,而next.js的模板使用NextPage来制作页面,而不是我通常在javascript中看到的(又名export default function Protected(props))。
那么,我如何将export async function getServerSideProps({ req, res, query })函数合并到我的打字脚本代码中呢?我不知道如何在NextPage页面中拥有一个单独的getServerSideProps函数。

brgchamk

brgchamk1#

您应该能够通过将getServerSideProps的类型声明为GetServerSideProps来在TS文件中声明getServerSideProps:

import { GetServerSideProps } from 'next';

export const getServerSideProps: GetServerSideProps = async ({ req, res, query }) => {
   ... 
}

相关问题