Search code examples
javascriptnode.jsreactjsnext.js

Next.js form works locally but not on live server


I have been implementing a Next.js app for a side project of mine. It is a basic brochure-style site with a contact form.

The form works perfectly fine when the site is run locally, however I have just published the site to Netlify and now when submitting a form I encounter the following error:

POST https://dux.io/api/form 404
Uncaught (in promise) Error: Request failed with status code 404
at e.exports (contact.js:9)
at e.exports (contact.js:16)
at XMLHttpRequest.d.(/contact/anonymous function) (https://dux.io/_next/static/cFeeqtpSGmy3dLZAZZWRt/pages/contact.js:9:4271)

Any help would be extremely appreciated!

This is my Form Submit function:

async handleSubmit(e) {
e.preventDefault();

const { name, email, option, message } = this.state;

const form = await axios.post('/api/form', {
  name,
  email,
  option,
  message
});

this.setState(initialState);}

This is my server.js file:

const express = require('express');
const next = require('next');
const bodyParser = require('body-parser');
const mailer = require('./mailer');
const compression = require('compression');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();
  server.use(compression());
  server.use(bodyParser.json());

  server.post('/api/form', (req, res) => {
    const { email = '', name = '', option = '', message = '' } = req.body;
    mailer({ email, name, option, text: message })
      .then(() => {
        console.log('success');
        res.send('success');
      })
      .catch(error => {
        console.log('failed', error);
        res.send('badddd');
      });
  });

  server.get('*', (req, res) => {
    return handle(req, res);
  });

  server.listen(3000, err => {
    if (err) throw err;
    console.log('> Read on http://localhost:3000');
  });
});


Solution

  • It looks like nextjs tries to render the /api/form page and you get a not found with that.

    Please make sure you start the server with node server.js instead of next start.