Next Js getServersideProps in Typescript

Last updated : Jul 30, 2023 12:00 AM

The Type for Next Js's getServerSideProps() function is GetServerSideProps. Here is a simple example of how to type getServerSideProps in Next Js.

import type { GetServerSideProps } from 'next'

interface Order {
    firstName: string
    lastName: string
    orderNo: string
}
const OrderPage = (order: Order) => {
  return (
    <>
        <p>{order.firstName}</p>
        <p>{order.lastName}</p>
        <p>{order.orderNo}</p>
    </>
  )
}
export const getServerSideProps: GetServerSideProps = async () => {
  return {
    props: {
      order: {
        firstName: 'Donald',
        lastName: 'Duck',
        orderNo: 'DL100'
      }
    }
  }
}
export default Home

In case you wonder, my _app.tsx extracts order from the page props and passes it to the component.

<Component {...pageProps.order} />

My getServerSideProps() function returns the Order object. That's what my Next Js page OrderPage receives as a prop. Therefore, I need an interface to type the Order object.

Lance

By: Lance

Hi, I'm Lance Raney, a dedicated Fullstack Developer based in Oklahoma with over 15 years of exp

Read more...