diff --git a/hocs/withFallback.js b/hocs/withFallback.js index 4c67c66..6bdc9f5 100644 --- a/hocs/withFallback.js +++ b/hocs/withFallback.js @@ -1,3 +1,5 @@ +import Head from "next/head"; +import Error from "next/error"; import { useRouter } from "next/router"; import styled from "styled-components"; import LoadingAnimation from "../components/LoadingAnimation"; @@ -12,20 +14,40 @@ const Center = styled.div` /** * HOC for statically rendered page with fallback activated - * @param {} WrappedComponent + * @param {JSX} WrappedComponent + * @param {string} propFetched name of the prop to check for redirects */ -export default function withFallback(WrappedComponent) { +export default function withFallback(WrappedComponent, propFetched) { const withFallbackWrapper = (props) => { const router = useRouter(); if (router.isFallback) { return (
- +
); } + /** + * Because we're using fallback: true on static generation next won't automatically redirect to 404 + * when an element doesn't exit on the API, so we're doing it manually here by checking if the prop that + * is supposed to be fetch exists + * + * This includes setting the noindex header because static files always return a status 200 + * but the rendered not found page page should obviously not be indexed + */ + if (!props[propFetched] || typeof props[propFetched] === "undefined") { + return ( + <> + + + + + + ); + } + return ; }; diff --git a/pages/_errors.js b/pages/_errors.js new file mode 100644 index 0000000..e4bad40 --- /dev/null +++ b/pages/_errors.js @@ -0,0 +1,40 @@ +import React from "react"; +import styled from "styled-components"; +import PageLayout from "../components/layouts/PageLayout"; + +const Center = styled.div` + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + + height: 100vh; + + text-align: center; +`; + +const StatusCode = styled.p` + color: ${(props) => props.theme.primary}; +`; + +function Error({ statusCode }) { + return ( + +
+ {statusCode} +

+ {statusCode + ? `An error occurred on server` + : "An error occurred on client"} +

+
+
+ ); +} + +Error.getInitialProps = ({ res, err }) => { + const statusCode = res ? res.statusCode : err ? err.statusCode : 404; + return { statusCode }; +}; + +export default Error;