Next.js: Is throwing an unnecessary error when getStaticProps & getServerSideProps are undefined

Created on 24 Mar 2020  路  5Comments  路  Source: vercel/next.js

Bug report

Describe the bug

When getStaticProps and getServerSideProps exist both as an export, is throwing an error.

You can not use getStaticProps with getServerSideProps. To use SSG, please remove getServerSideProps

Looks OK, however, IMO it should throw this error only when both are functions. With this, it will be possible to use conditional exports.

export let getStaticProps
export let getServerSideProps

if(process.env.SSG) {
  getStaticProps = loadData
} else { 
  getServerSideProps = loadData
}

To Reproduce

export const getStaticProps = undefined
export const getServerSideProps = undefined

Expected behavior

With this:

export const getStaticProps = undefined
export const getServerSideProps = async ctx => ({ props: { itWorks: false } })

I expect that getServerSideProps is executed because getStaticProps is not defined.

With this:

export const getStaticProps = async ctx => ({ props: { itWorks: false } })
export const getServerSideProps = undefined

I expect that getStaticProps is executed because getServerSideProps is not defined.

story needs investigation

All 5 comments

This behavior will not / should not work by design:

export let getStaticProps
export let getServerSideProps

if(process.env.SSG) {
  getStaticProps = loadData
} else { 
  getServerSideProps = loadData
}

You must export a function.

If the above works when you're not mixing the two, we need to issue a patch release to disallow such behavior.

Ok @Timer ! But why this restriction instead of just ignore when they aren't functions?

Because getStaticProps en getServerSideProps are tree shaken from browser bundles and what you're trying to do (dynamic assignment) makes it impossible to tree shake it.

Ok. In that case, it makes sense to me! Thanks to clarifying this @timneutkens

Is there a way to use them both together?
I mean...my first thought was to use static props for some info (like version, port, path, envType, etc) and serverside props to api values.

Was this page helpful?
0 / 5 - 0 ratings