Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A small babel transform to switch `getStaticProps` to `getServerProps` in nextjs
// getStaticProps, which we use as the primary method for data fetching on all our pages,
// runs at build time and generates page data statically. this data is not regenerated
// unless the site is rebuilt, a lot like a static site generator. therefore, it's not
// helpful when you are trying to live preview content changes without rebuilding the entire
// site, even though its great for performance in production.
// In order to solve this, we run this script before pushing the preview version of the website,
// which replaces `getStaticProps` with `getServerProps`, a method with the same signature that
// dynamically fetches data fresh on every page load, making it excellent for fast-changing data,
// which is just what we need for a preview environment.
// The nextjs team is working on a "next-native" solution to the preview content problem, as
// soon as this is released we will remove this script and shift our code into the native solution.
// The result may look something like returning { props: { foo: 'bar' }, preview: true } from
// getStaticProps.
const babel = require('@babel/core')
const glob = require('glob')
const path = require('path')
const fs = require('fs')
const prettier = require('prettier')
`${path.join(__dirname, '../pages')}/**/*.+(jsx|tsx)`,
(err, files) => {
if (err) throw err => {
babel.transformFile(file, babelConfig, (err, result) => {
if (err) throw err
prettier.format(result.code, {
parser: file.match(/\.tsx$/) ? 'typescript' : 'babel',
semi: false,
singleQuote: true
() => console.log(`Transformed: ${file}`)
const babelConfig = {
plugins: [
['@babel/plugin-syntax-typescript', { isTSX: true }],
function staticToServerPropsPlugin({ types: t }) {
return {
visitor: {
FunctionDeclaration(_path) {
if ( === 'unstable_getStaticProps') { = t.identifier('unstable_getServerProps')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment