getServerSideProps API

If you export an

async function called getServerSideProps from a page, Blitz will pre-render this page on each request using the data returned by getServerSideProps.

  1. export async function getServerSideProps(context) { return { props: {}, // will be passed to the page component as props }}

The

context parameter is an object containing the following keys:

Note: You can import modules in top-level scope for use in

getServerSideProps. Imports used in getServerSideProps will not be bundled for the client-side, as explained below.

Simple example

Here’s an example which uses

getServerSideProps to fetch data at request time and pre-renders it.

  1. function Page({data}) { // Render data...}// This gets called on every requestexport async function getServerSideProps() { // Fetch data using a blitz query or a third-party API const data = /* .. */ // Pass data to the page via props return {props: {data}}}export default Page

TypeScript: Use GetServerSideProps

For TypeScript, you can use the

GetServerSideProps type from blitz:

  1. import {GetServerSideProps} from "blitz"export const getServerSideProps: GetServerSideProps = async (context) => { // ...}

If you want to get inferred typings for your props, you can use

InferGetServerSidePropsType<typeof getServerSideProps>, like this:

  1. import { InferGetServerSidePropsType } from 'blitz'type Data = { ... }export const getServerSideProps = async () => { const res = await fetch('https://.../data') const data: Data = await res.json() return { props: { data, }, }}function Page({ data }: InferGetServerSidePropsType<typeof getServerSideProps>) { // will resolve posts to type Data}export default Page

Technical details

Only runs on server-side

getServerSideProps only runs on server-side and never runs on the browser. If a page uses getServerSideProps , then:

  • When you request this page directly, getServerSideProps runs at the request time, and this page will be pre-rendered with the returned props.
  • When you request this page on client-side page transitions through <Link> or router (documentation), Blitz sends an API request to the server, which runs getServerSideProps. It’ll return JSON that contains the result of running getServerSideProps, and the JSON will be used to render the page. All this work will be handled automatically by Blitz, so you don’t need to do anything extra as long as you have getServerSideProps defined.

You can use

this tool to verify what Blitz eliminates from the client-side bundle.

Only allowed in a page

getServerSideProps can only be exported from a page. You can’t export it from non-page files.