I have success page which has to be displayed when the form is submitted in Gatsby. But the user can directly visit /success page. Is there any way to prevent it?
I have success page which has to be displayed when the form is submitted in Gatsby. But the user can directly visit /success page. Is there any way to prevent it?
There are a couple ways to do this. One is outlined here by Gatsby and involves creating a client-only route (that is, Gatsby won't have React render it server-side, but will route to your component on the client/browser). That looks something like this:
exports.onCreatePage = async ({ page, actions }) => {
const { createPage } = actions
// page.matchPath is a special key that's used for matching pages
// only on the client.
if (page.path.match(/^\/app/)) {
page.matchPath = "/app/*"
// Update the page.
createPage(page)
}
}
A route I've taken to do this, especially when it's not a particularly sensitive page, is to render the page, but check for some condition on render and use navigate if the condition isn't satisfied.
For example, if you stored formSubmitted in AppContext, you could do something like this:
import React, { useContext } from "react"
import { navigate } from "gatsby"
const SuccessPage = () => {
const { formSubmitted } = useContext(AppContext)
return formSubmitted ? <div>Thanks!</div> : navigate("/contact", { replace: true })
}