Skip to content

Commit

Permalink
Remove unstable_ prefix from new methods (#10723)
Browse files Browse the repository at this point in the history
* Rename getServerProps to getServerSideProps

* Remove unstable_ prefix from new methods

* Add error when legacy methods are detected

* Add legacy methods for babel transform

* Add unstable_getServerSideProps also

* Apply suggestions from code review

Co-Authored-By: Joe Haddad <joe.haddad@zeit.co>

* Update types import

Co-authored-by: Joe Haddad <timer150@gmail.com>
  • Loading branch information
ijjk and Timer committed Feb 27, 2020
1 parent 2789e7e commit c9d9f11
Show file tree
Hide file tree
Showing 59 changed files with 336 additions and 228 deletions.
10 changes: 5 additions & 5 deletions errors/invalid-getstaticpaths-value.md
@@ -1,15 +1,15 @@
# Invalid unstable_getStaticPaths Return Value
# Invalid getStaticPaths Return Value

#### Why This Error Occurred

In one of the page's `unstable_getStaticPaths` the return value had the incorrect shape.
In one of the page's `getStaticPaths` the return value had the incorrect shape.

#### Possible Ways to Fix It

Make sure to return the following shape from `unstable_getStaticPaths`:
Make sure to return the following shape from `getStaticPaths`:

```js
export async function unstable_getStaticPaths() {
export async function getStaticPaths() {
return {
paths: Array<string | { params: { [key: string]: string } }>,
fallback: boolean
Expand All @@ -23,7 +23,7 @@ There are two required properties:
- You may return a [String](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) or an [Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) that explicitly defines all URL `params`.
```js
// pages/blog/[slug].js
export async function unstable_getStaticPaths() {
export async function getStaticPaths() {
return {
paths: [
// String variant:
Expand Down
8 changes: 4 additions & 4 deletions errors/invalid-getstaticprops-value.md
@@ -1,15 +1,15 @@
# Invalid unstable_getStaticProps Return Value
# Invalid getStaticProps Return Value

#### Why This Error Occurred

In one of the page's `unstable_getStaticProps` the return value had the incorrect shape.
In one of the page's `getStaticProps` the return value had the incorrect shape.

#### Possible Ways to Fix It

Make sure to return the following shape from `unstable_getStaticProps`:
Make sure to return the following shape from `getStaticProps`:

```js
export async function unstable_getStaticProps() {
export async function getStaticProps() {
return {
props: { [key: string]: any }
}
Expand Down
2 changes: 1 addition & 1 deletion examples/z-experimental-next-news/pages/ask.js
Expand Up @@ -4,7 +4,7 @@ import Stories from '../components/stories'
import getStories from '../lib/get-stories'

// eslint-disable-next-line camelcase
export async function unstable_getStaticProps() {
export async function getStaticProps() {
const page = 1
const stories = await getStories('askstories', { page })
return { props: { page, stories } }
Expand Down
2 changes: 1 addition & 1 deletion examples/z-experimental-next-news/pages/index.js
Expand Up @@ -4,7 +4,7 @@ import Stories from '../components/stories'
import getStories from '../lib/get-stories'

// eslint-disable-next-line camelcase
export async function unstable_getStaticProps() {
export async function getStaticProps() {
const page = 1
const stories = await getStories('topstories', { page })
return { props: { page, stories } }
Expand Down
2 changes: 1 addition & 1 deletion examples/z-experimental-next-news/pages/item/[id].js
Expand Up @@ -4,7 +4,7 @@ import Item from '../../components/item'
import getItem from '../../lib/get-item'
import getComments from '../../lib/get-comments'

export async function unstable_getStaticProps({ params }) {
export async function getStaticProps({ params }) {
const story = await getItem(params.id)
return { props: { story } }
}
Expand Down
2 changes: 1 addition & 1 deletion examples/z-experimental-next-news/pages/jobs.js
Expand Up @@ -4,7 +4,7 @@ import Stories from '../components/stories'
import getStories from '../lib/get-stories'

// eslint-disable-next-line camelcase
export async function unstable_getStaticProps() {
export async function getStaticProps() {
const page = 1
const stories = await getStories('jobstories', { page })
return { props: { page, stories } }
Expand Down
2 changes: 1 addition & 1 deletion examples/z-experimental-next-news/pages/newest.js
Expand Up @@ -4,7 +4,7 @@ import Stories from '../components/stories'
import getStories from '../lib/get-stories'

// eslint-disable-next-line camelcase
export async function unstable_getStaticProps() {
export async function getStaticProps() {
const page = 1
const stories = await getStories('newstories', { page })
return { props: { page, stories } }
Expand Down
2 changes: 1 addition & 1 deletion examples/z-experimental-next-news/pages/news/[id].js
Expand Up @@ -4,7 +4,7 @@ import Stories from '../../components/stories'
import getStories from '../../lib/get-stories'

// eslint-disable-next-line camelcase
export async function unstable_getStaticProps({ params }) {
export async function getStaticProps({ params }) {
const page = Number(params.id)
const stories = await getStories('topstories', { page })
return { props: { page, stories } }
Expand Down
2 changes: 1 addition & 1 deletion examples/z-experimental-next-news/pages/show.js
Expand Up @@ -4,7 +4,7 @@ import Stories from '../components/stories'
import getStories from '../lib/get-stories'

// eslint-disable-next-line camelcase
export async function unstable_getStaticProps() {
export async function getStaticProps() {
const page = 1
const stories = await getStories('showstories', { page })
return { props: { page, stories } }
Expand Down
13 changes: 10 additions & 3 deletions packages/next/build/babel/plugins/next-ssg-transform.ts
Expand Up @@ -8,14 +8,21 @@ import {

const pageComponentVar = '__NEXT_COMP'

export const EXPORT_NAME_GET_STATIC_PROPS = 'unstable_getStaticProps'
export const EXPORT_NAME_GET_STATIC_PATHS = 'unstable_getStaticPaths'
export const EXPORT_NAME_GET_SERVER_PROPS = 'unstable_getServerSideProps'
export const EXPORT_NAME_GET_STATIC_PROPS = 'getStaticProps'
export const EXPORT_NAME_GET_STATIC_PATHS = 'getStaticPaths'
export const EXPORT_NAME_GET_SERVER_PROPS = 'getServerSideProps'

const ssgExports = new Set([
EXPORT_NAME_GET_STATIC_PROPS,
EXPORT_NAME_GET_STATIC_PATHS,
EXPORT_NAME_GET_SERVER_PROPS,

// legacy methods added so build doesn't fail from importing
// server-side only methods
`unstable_getStaticProps`,
`unstable_getStaticPaths`,
`unstable_getServerProps`,
`unstable_getServerSideProps`,
])

type PluginState = {
Expand Down
2 changes: 1 addition & 1 deletion packages/next/build/index.ts
Expand Up @@ -779,7 +779,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
// For a dynamic SSG page, we did not copy its data exports and only
// copy the fallback HTML file (if present).
// We must also copy specific versions of this page as defined by
// `unstable_getStaticPaths` (additionalSsgPaths).
// `getStaticPaths` (additionalSsgPaths).
const extraRoutes = additionalSsgPaths.get(page) || []
for (const route of extraRoutes) {
await moveExportedPage(route, route, true, 'html')
Expand Down
53 changes: 37 additions & 16 deletions packages/next/build/utils.ts
Expand Up @@ -15,7 +15,7 @@ import { recursiveReadDir } from '../lib/recursive-readdir'
import { getRouteMatcher, getRouteRegex } from '../next-server/lib/router/utils'
import { isDynamicRoute } from '../next-server/lib/router/utils/is-dynamic'
import { findPageFile } from '../server/lib/find-page-file'
import { Unstable_getStaticPaths } from '../next-server/server/load-components'
import { GetStaticPaths } from 'next/types'

const fileGzipStats: { [k: string]: Promise<number> } = {}
const fsStatGzip = (file: string) => {
Expand Down Expand Up @@ -500,7 +500,7 @@ export async function getPageSizeInKb(

export async function buildStaticPaths(
page: string,
unstable_getStaticPaths: Unstable_getStaticPaths
getStaticPaths: GetStaticPaths
): Promise<{ paths: string[]; fallback: boolean }> {
const prerenderPaths = new Set<string>()
const _routeRegex = getRouteRegex(page)
Expand All @@ -509,7 +509,7 @@ export async function buildStaticPaths(
// Get the default list of allowed params.
const _validParamKeys = Object.keys(_routeMatcher(page))

const staticPathsResult = await unstable_getStaticPaths()
const staticPathsResult = await getStaticPaths()

const expectedReturnVal =
`Expected: { paths: [], fallback: boolean }\n` +
Expand All @@ -521,7 +521,7 @@ export async function buildStaticPaths(
Array.isArray(staticPathsResult)
) {
throw new Error(
`Invalid value returned from unstable_getStaticPaths in ${page}. Received ${typeof staticPathsResult} ${expectedReturnVal}`
`Invalid value returned from getStaticPaths in ${page}. Received ${typeof staticPathsResult} ${expectedReturnVal}`
)
}

Expand All @@ -531,15 +531,15 @@ export async function buildStaticPaths(

if (invalidStaticPathKeys.length > 0) {
throw new Error(
`Extra keys returned from unstable_getStaticPaths in ${page} (${invalidStaticPathKeys.join(
`Extra keys returned from getStaticPaths in ${page} (${invalidStaticPathKeys.join(
', '
)}) ${expectedReturnVal}`
)
}

if (typeof staticPathsResult.fallback !== 'boolean') {
throw new Error(
`The \`fallback\` key must be returned from unstable_getStaticPaths in ${page}.\n` +
`The \`fallback\` key must be returned from getStaticPaths in ${page}.\n` +
expectedReturnVal
)
}
Expand All @@ -548,7 +548,7 @@ export async function buildStaticPaths(

if (!Array.isArray(toPrerender)) {
throw new Error(
`Invalid \`paths\` value returned from unstable_getStaticProps in ${page}.\n` +
`Invalid \`paths\` value returned from getStaticProps in ${page}.\n` +
`\`paths\` must be an array of strings or objects of shape { params: [key: string]: string }`
)
}
Expand All @@ -572,7 +572,7 @@ export async function buildStaticPaths(
const invalidKeys = Object.keys(entry).filter(key => key !== 'params')
if (invalidKeys.length) {
throw new Error(
`Additional keys were returned from \`unstable_getStaticPaths\` in page "${page}". ` +
`Additional keys were returned from \`getStaticPaths\` in page "${page}". ` +
`URL Parameters intended for this dynamic route must be nested under the \`params\` key, i.e.:` +
`\n\n\treturn { params: { ${_validParamKeys
.map(k => `${k}: ...`)
Expand All @@ -593,7 +593,7 @@ export async function buildStaticPaths(
throw new Error(
`A required parameter (${validParamKey}) was not provided as ${
repeat ? 'an array' : 'a string'
} in unstable_getStaticPaths for ${page}`
} in getStaticPaths for ${page}`
)
}

Expand Down Expand Up @@ -634,14 +634,35 @@ export async function isPageStatic(
}

const hasGetInitialProps = !!(Comp as any).getInitialProps
const hasStaticProps = !!mod.unstable_getStaticProps
const hasStaticPaths = !!mod.unstable_getStaticPaths
const hasServerProps = !!mod.unstable_getServerSideProps
const hasStaticProps = !!mod.getStaticProps
const hasStaticPaths = !!mod.getStaticPaths
const hasServerProps = !!mod.getServerSideProps
const hasLegacyServerProps = !!mod.unstable_getServerProps
const hasLegacyStaticProps = !!mod.unstable_getStaticProps
const hasLegacyStaticPaths = !!mod.unstable_getStaticPaths
const hasLegacyStaticParams = !!mod.unstable_getStaticParams

if (hasLegacyStaticParams) {
throw new Error(
`unstable_getStaticParams was replaced with unstable_getStaticPaths. Please update your code.`
`unstable_getStaticParams was replaced with getStaticPaths. Please update your code.`
)
}

if (hasLegacyStaticPaths) {
throw new Error(
`unstable_getStaticPaths was replaced with getStaticPaths. Please update your code.`
)
}

if (hasLegacyStaticProps) {
throw new Error(
`unstable_getStaticProps was replaced with getStaticProps. Please update your code.`
)
}

if (hasLegacyServerProps) {
throw new Error(
`unstable_getServerProps was replaced with getServerSideProps. Please update your code.`
)
}

Expand All @@ -663,14 +684,14 @@ export async function isPageStatic(
// A page cannot have static parameters if it is not a dynamic page.
if (hasStaticProps && hasStaticPaths && !pageIsDynamic) {
throw new Error(
`unstable_getStaticPaths can only be used with dynamic pages, not '${page}'.` +
`getStaticPaths can only be used with dynamic pages, not '${page}'.` +
`\nLearn more: https://nextjs.org/docs#dynamic-routing`
)
}

if (hasStaticProps && pageIsDynamic && !hasStaticPaths) {
throw new Error(
`unstable_getStaticPaths is required for dynamic SSG pages and is missing for '${page}'.` +
`getStaticPaths is required for dynamic SSG pages and is missing for '${page}'.` +
`\nRead more: https://err.sh/next.js/invalid-getstaticpaths-value`
)
}
Expand All @@ -681,7 +702,7 @@ export async function isPageStatic(
;({
paths: prerenderRoutes,
fallback: prerenderFallback,
} = await buildStaticPaths(page, mod.unstable_getStaticPaths))
} = await buildStaticPaths(page, mod.getStaticPaths))
}

const config = mod.config || {}
Expand Down
33 changes: 19 additions & 14 deletions packages/next/build/webpack/loaders/next-serverless-loader.ts
Expand Up @@ -217,10 +217,15 @@ const nextServerlessLoader: loader.Loader = function() {
const Component = ComponentInfo.default
export default Component
export const unstable_getStaticProps = ComponentInfo['unstable_getStaticProp' + 's']
export const unstable_getStaticParams = ComponentInfo['unstable_getStaticParam' + 's']
export const getStaticProps = ComponentInfo['getStaticProp' + 's']
export const getStaticPaths = ComponentInfo['getStaticPath' + 's']
export const getServerSideProps = ComponentInfo['getServerSideProp' + 's']
// kept for detecting legacy exports
export const unstable_getStaticProps = ComponentInfo['unstable_getStaticProp' + 's']
export const unstable_getStaticPaths = ComponentInfo['unstable_getStaticPath' + 's']
export const unstable_getServerSideProps = ComponentInfo['unstable_getServerSideProp' + 's']
export const unstable_getServerProps = ComponentInfo['unstable_getServerProp' + 's']
${dynamicRouteMatcher}
${handleRewrites}
Expand All @@ -241,9 +246,9 @@ const nextServerlessLoader: loader.Loader = function() {
App,
Document,
buildManifest,
unstable_getStaticProps,
unstable_getServerSideProps,
unstable_getStaticPaths,
getStaticProps,
getServerSideProps,
getStaticPaths,
reactLoadableManifest,
canonicalBase: "${canonicalBase}",
buildId: "${buildId}",
Expand Down Expand Up @@ -275,7 +280,7 @@ const nextServerlessLoader: loader.Loader = function() {
${page === '/_error' ? `res.statusCode = 404` : ''}
${
pageIsDynamicRoute
? `const params = fromExport && !unstable_getStaticProps && !unstable_getServerSideProps ? {} : dynamicRouteMatcher(parsedUrl.pathname) || {};`
? `const params = fromExport && !getStaticProps && !getServerSideProps ? {} : dynamicRouteMatcher(parsedUrl.pathname) || {};`
: `const params = {};`
}
${
Expand Down Expand Up @@ -320,7 +325,7 @@ const nextServerlessLoader: loader.Loader = function() {
const previewData = tryGetPreviewData(req, res, options.previewProps)
const isPreviewMode = previewData !== false
let result = await renderToHTML(req, res, "${page}", Object.assign({}, unstable_getStaticProps ? {} : parsedUrl.query, nowParams ? nowParams : params, _params, isFallback ? { __nextFallback: 'true' } : {}), renderOpts)
let result = await renderToHTML(req, res, "${page}", Object.assign({}, getStaticProps ? {} : parsedUrl.query, nowParams ? nowParams : params, _params, isFallback ? { __nextFallback: 'true' } : {}), renderOpts)
if (_nextData && !fromExport) {
const payload = JSON.stringify(renderOpts.pageData)
Expand All @@ -331,7 +336,7 @@ const nextServerlessLoader: loader.Loader = function() {
'Cache-Control',
isPreviewMode
? \`private, no-cache, no-store, max-age=0, must-revalidate\`
: unstable_getServerSideProps
: getServerSideProps
? \`no-cache, no-store, must-revalidate\`
: \`s-maxage=\${renderOpts.revalidate}, stale-while-revalidate\`
)
Expand All @@ -350,19 +355,19 @@ const nextServerlessLoader: loader.Loader = function() {
if (err.code === 'ENOENT') {
res.statusCode = 404
const result = await renderToHTML(req, res, "/_error", parsedUrl.query, Object.assign({}, options, {
unstable_getStaticProps: undefined,
unstable_getStaticPaths: undefined,
unstable_getServerSideProps: undefined,
getStaticProps: undefined,
getStaticPaths: undefined,
getServerSideProps: undefined,
Component: Error
}))
return result
} else {
console.error(err)
res.statusCode = 500
const result = await renderToHTML(req, res, "/_error", parsedUrl.query, Object.assign({}, options, {
unstable_getStaticProps: undefined,
unstable_getStaticPaths: undefined,
unstable_getServerSideProps: undefined,
getStaticProps: undefined,
getStaticPaths: undefined,
getServerSideProps: undefined,
Component: Error,
err
}))
Expand Down

0 comments on commit c9d9f11

Please sign in to comment.