Published on

Next.jsで特定のページを除外(exclude)したい時のやり方

Authors
  • avatar
    Name
    ssu
    Twitter

Next.jsで特定のページを除外(exclude)したい時のやり方

Next.jsでこのページはbuild時、export時に除外したいという場面があるかと思います。

ただ、下記の通り、これ実は公式でサポートされていなくて現時点ではまともなやり方がありません。 (やるなら404をgetinitialPropsでやるしかないよと書いてあります)

You can't really exclude them. But you could render a 404 page in getInitialProps. We don't have short term plans to add this feature cause you can lock down the pages using the programmatic (custom server) api. -- timneutkens

つまり、page/下にあるものは全てbuildの対象になってしまうんです。

そこで、避けるやり方としては、そのページをbuildするときは404を返すのようなことが 対処方法としてあります。

それを紹介します。

const whiteList = ['television1', 'television2, 'television3']; const useWhiteListParams = () => { const router = useRouter(); const { tv } = router.query; useEffect(() => { if(!whiteList.includes(tv)) { router.push(/404); } }, [tv]) }

whitelistを作って、それに該当しない場合は404を返すという方法です。 これはダサいですけど、これしかやり方がないのが現状です。 ただ、RFCが出ているので将来的には実装されるかもしれません

参考: nextjs-dynamic-routing-exclude