Home > Net >  How do I run getServerSideProps in a typescript NextPage page?
How do I run getServerSideProps in a typescript NextPage page?

Time:10-24

This is the type of page that I want to replicate (code from 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
    },
  }
}

But I've grown accustomed to making next.js pages like this:
"protected.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

I'm using typescript and the next.js scaffolded boilerplate for typescript uses NextPage to make the pages instead of what I normally see in javascript (aka export default function Protected(props)).

So how do I incorporate the export async function getServerSideProps({ req, res, query }) function into my typescript code? I don't see how I can have a separate function getServerSideProps in a NextPage page.

CodePudding user response:

You should be able to declare getServerSideProps in your TS file by declaring its type to GetServerSideProps:

import { GetServerSideProps } from 'next';

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