DEV Community

Nikolas ⚡️
Nikolas ⚡️

Posted on • Updated on • Originally published at nikolasbarwicki.com

Redirect to a page from Next.js API Route

The problem

If you want to redirect a user to a “Thank You” page after signing up for your newsletter, and you’re using Next.js with its API routes, you can implement this functionality with just a few lines of code.

Example

Please note that the redirect function will not work with fetch. The API request must be initiated by a <form>. The following is an example Next component that will be used to call our API route.

export function Newsletter() {
  return (
    <form method="POST" action="/api/create-subscriber">
      <h2>
   Stay up to date
      </h2>
      <p>
        Get notified when I publish something new, and unsubscribe at any time.
      </p>
      <div>
        <input
          id="email"
          name="email"
          type="email"
          placeholder="Email address"
          aria-label="Email address"
          required
        />
        <button type="submit">
          Join
        </button>
      </div>
    </form>
  )
}
Enter fullscreen mode Exit fullscreen mode

As you can see, we are not handling the form state using hooks, and we’re not defining a handleSubmit function or passing anything to the onSubmit prop. The action prop should point to the API route that handles form submissions.

We have to use Next.js API routes because we need to attach the API key, which cannot be exposed to users in the browser.

API Route

When the user clicks the “Join” button, the form is submitted, and the form data, including the email, is passed via the request body.

export default async function handler(req, res) {
  const { email } = req.body
  try {
    await handleFormInputAsync({ email })
    res.redirect(307, /thank-you)
  } catch (err) {
    res.status(500).send({ error: failed to fetch data })
  }
}
Enter fullscreen mode Exit fullscreen mode

The handleFormInputAsync helper sends a request to our email service provider, including the user’s email and our unique private API key. If the request is handled successfully, the user will be redirected to the “Thank You” page in our front-end application.

Why api redirects don’t work with fetch

Fetch requests in the browser do not allow redirects to change the current document. When a redirect is initiated from a fetch call, the browser does not follow the document and the request can only be used to retrieve data. This can be seen in the Chrome Network tab where the request type is shown as “fetch/Redirect”. This restriction is in place to prevent scripts from changing the document and causing chaos. Attempting to follow the redirect manually, using { redirect : “manual” }, will result in another request being made to the redirected location, but the redirected location is not returned and the new page cannot be navigated to using Javascript.

⚡️ Action Points

Top comments (0)