Next Js getServersideProps in Typescript

Last updated : December 18, 2022

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
Lance is a software engineer with over 15 years of experience in full-stack software development.
Read more...

Comments are disabled

No Comments