Skip to content

Commit

Permalink
adding 404 redirect when dynamically generated page doesn't exists
Browse files Browse the repository at this point in the history
  • Loading branch information
RmnRss committed Sep 15, 2020
1 parent acba97d commit 39899a3
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 3 deletions.
28 changes: 25 additions & 3 deletions hocs/withFallback.js
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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 (
<Center>
<LoadingAnimation message={"Loading..."} />
<LoadingAnimation message={"Loading Page..."} />
</Center>
);
}

/**
* 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 (
<>
<Head>
<meta name="robots" content="noindex" />
</Head>
<Error statusCode={404} />
</>
);
}

return <WrappedComponent {...props} />;
};

Expand Down
40 changes: 40 additions & 0 deletions pages/_errors.js
Original file line number Diff line number Diff line change
@@ -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 (
<PageLayout>
<Center>
<StatusCode>{statusCode}</StatusCode>
<p>
{statusCode
? `An error occurred on server`
: "An error occurred on client"}
</p>
</Center>
</PageLayout>
);
}

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

export default Error;

0 comments on commit 39899a3

Please sign in to comment.