John
John

Reputation: 95

How to setup a netlify form in Nuxt

When I navigate to a form using vue-router by adding a link with a <router-link> element, the form does not work. When I hit submit I get a 404 response.

However, if I navigate to it using an <a> tag (triggering a page reload) then it works perfectly.

I suspect that this has to do with the page rendering as a SPA and for some reason not loading an important part of the form for Netlify unless the form page is reloaded? Why is this happening and is there an elegant solution to the problem? I could just replace all links to forms with tags but I'm sure that there is a better solution, I just don't understand the problem well enough to find it.

For context, I am using Nuxt. The forms are recognized by Netlify on the backend and can accept submission with the tag link so that is not the problem.

Upvotes: 3

Views: 1666

Answers (1)

kissu
kissu

Reputation: 46761

Since you're using Nuxt, you probably should go SSG/full static with target: 'static' (hostable on Netlify-like platforms) or with target: 'server' (hostable on Heroku-like platforms) but at any point, you should have ssr: true (default value). When you do have this, the biggest part is done.

In Nuxt, you should use <nuxt-link> rather than <router-link>, it works exactly the same (takes the same params etc) but it's more specific to Nuxt and SSR/SSG compatible while <router-link> is not. More details here: https://nuxtjs.org/docs/2.x/features/nuxt-components#the-nuxtlink-component

So, with all of this it should already work great. If it's not, I will gladly help you spot the issue if you have a github repo.


An alternative solution can be to use some form without any SSR dependency like Formspree: https://formspree.io/ (works fine with any SPA)

It works great, really simple. But I'd rather invite you to make a proper SSR form since you're using Nuxt.


PS: use <a> tags only for external links aka the ones which do not start with your domain name, nothing else. A follow of this kind of link is like a hard refresh and should be avoided at all costs.


EDIT: how to deploy by cleaning the cache.

enter image description here


EDIT on how to achieve a working form:

<template>
  <div>
    <form
      netlify
      action="/"
      method="POST"
      name="Contact"
    >
      <input type="hidden" name="form-name" value="Contact" />
      <!-- ... -->
    </form>
  </div>
</template>

As told in the docs:

[...] inject a hidden input named form-name [...] and the hidden form-name input’s value matches the name attribute of form

Working fine. Could add a honeypot to it to make it even more secure!

enter image description here

Upvotes: 4

Related Questions