Open source changelog

Follow the evolution of Gatsby.

Subscribe to updates
 

Description

getServerData does not currently have any types around it. This code change should allow developers to have type safety within this method for each page.

Note: this does change the type of the old IServerData's headers from a Record to a Map. There were inconsistencies in it's typing, so this syncs them up. Please mention any concerns there may be with this conversion.

Using the example from Gatsby's SSR doc, and given the following type: type ServerDataProps = { message?: string, status?: string, }

We can get type safety in an anonymous function using the given shorthand: export const getServerData: GetServerData<ServerDataProps> = async (props) => { try { const res = await fetch(`https://dog.ceo/api/breeds/image/random`) if (!res.ok) { throw new Error(`Response failed`) } return { props: await res.json(), } } catch (error) { return { status: 500, headers: new Map(), props: {} } } }

Or if we use a named function, we can use the Props and Return types: export async function getServerData(props: GetServerDataProps): GetServerDataReturn<ServerDataProps> { try { const res = await fetch(`https://dog.ceo/api/breeds/image/random`) if (!res.ok) { throw new Error(`Response failed`) } return { props: await res.json(), } } catch (error) { return { status: 500, headers: new Map(), props: {} } } }

[sc-38899]