Static Form Submission To Laravel Using Next.js Api [Part 2]

Reece May • March 11, 2021 • 5 min read

nextjs tutorial react

This post will go through setting up your Next.js application to send your static form data to your Laravel application we setup in part one. If you haven't gone through that one yet, you might want to check it out here.

Overview

Points that I will cover during this article are the following:

  1. Setting up your basic Next.js application
  2. Creating your API handler class
  3. Creating a Simple HTML form to send data to the API
  4. Trying the system out

1. Setting up the Next.js application

Setting up a Next.js application is simple, I would say compared to trying to create a new application, running npx you can do the following: npx create-next-app static-form-front.

This will give you the default things you need to start, you can navigate to that folder and run npm run dev to boot up the dev server. It should be pretty quick.

That brief thing would be about it, if you have any questions, the Vercel docs would describe it better than myself :)

Creating an API function in Next.js

When you create a default application with Next.js you get the pages directory, under there is an index.js file and the api directory, there is a hello.js file, that would result in the URL, https://localhost:3000/api/hello when called.

That's a good thing to remember, it applies to directories names too, so you can create the URL using the directories and file name.

2. API endpoint for handling form submission

We will create our API route by creating a file under the pages/api directory, you can call the file contactus.js (or whatever is better for yourself)

In that file you can place the default code:

1export default async function contactus(req, res) {
2 //
3}

We are going to make sure that this only accepts post requests and fails when the honeypot value happens to be set, it would look like this now:

1// api/contactus.js
2export default async function contactus(req, res) {
3 
4 if (req.method !== 'POST') {
5 return res.status(400);
6 }
7 
8 // honeypot value
9 if (req.body?.website) {
10 return res.status(200);
11 }
12}

Then, naturally once we have filtered out those types of requests, we would want to send our data to the Laravel backend code.

We are going to use the included node-fetch with Next.js, which means we can call fetch from within the API.

Because the req body is just a string when posting, you are going to want to parse the body back to JSON to be able to send it to the Laravel application. So far we are going to have the following code for the fetch request:

1let body = JSON.parse(req.body)
2 
3const request = await fetch(
4 `${process.env.APP_URL}/api/static/contact`,
5 {
6 method: 'POST',
7 body: JSON.stringify(body),
8 }
9)

Now, the application URl can be set via the process.env.APP_URL, this means that it can be changed in the environment variables. You can then set it to the local dev URL for local work or the actual production one without having to hard code it.

But nothing will actually work at this point, you are probably wondering where the API token we generated comes into the mix?? Well, these values are set in the headers value.

We are going to add a headers property to the config value of fetch. The most important part is that we add the same header name we defined in our middleware, that was 'X-Static-Site-Token'. The value will be set via and environment variable to ensure we can change the value without having to hardcode a token value into the application.

1{
2 headers: {
3 'X-Static-Site-Token': process.env.APP_TOKEN, /** This header is the important point here */
4 'Content-Type': 'application/json', /** This header is needed for the POST data to be transformed into the correct structure, not just a string*/
5 'Accept': 'application/json',
6 "X-Requested-With": "XMLHttpRequest", /** This here, other that the accept, also lets Laravel to send back a JSON response */
7 },
8}

Once we have all the parts put together in the API handler, we should have a file that looks like the below version:

1// api/contactus.js
2export default async function contactus(req, res) {
3 
4 if (req?.method !== 'POST') {
5 return res.status(400);
6 }
7 
8 // honeypot value
9 if (req?.body?.website) {
10 return res.status(200);
11 }
12 
13 let body = JSON.parse(req.body)
14 
15 const request = await fetch(
16 `${process.env.APP_URL}/api/static/contact`,
17 {
18 method: 'POST',
19 body: JSON.stringify(body),
20 headers: {
21 'X-Static-Site-Token': process.env.APP_TOKEN, /** This header is the important point here */
22 'Content-Type': 'application/json',
23 'Accept': 'application/json',
24 "X-Requested-With": "XMLHttpRequest",
25 },
26 }
27 )
28 
29 if (request.status !== 201 ) {
30 let json = await request.json()
31 
32 throw new Error(json?.message || 'Failed to create new message');
33 }
34 
35 const json = await request.json()
36 
37 if (json.errors) {
38 console.error(json?.errors)
39 throw new Error('Failed to fetch, view log file for JSON errors')
40 }
41 
42 return res.status(201).json(json?.data || {});
43}

You will notice, that after the POST request, we then handle the response data, this is important.

⚠️ IMPORTANT: If you fail to return a response, JSON or string, the Vercel API will fail.

If we have not received a created response, we will through an error to the frontend. If there are errors from the Laravel controller, we then throw a general error and let the user or admin know to check the endpoints log file on Vercel.

Once we have passed all those possibilities, we then return the data to the end user as a Success :)

That would wrap up that part of the code.

3. Creating a Simple HTML form to send data to the API - The Frontend Code

We can make this work with a simple, and un-styled HTML form. This is because the pretty does not equal the working part :)

The file can be created and placed in a components directory at the root of the Next.js application, ./components/ContactUs.js.

The main thing to remember here is to intercept and cancel the Form submit event. i.e. using event.preventDefault() in the handler function that you attach to the <form> element, this prevents it from sending data back to the same page that won't know what to do with the information.

You can try a simple form layout for the frontend:

1import React, { useState } from 'react'
2 
3let Alert = ({ message, type = 'success'}) => {
4 return (
5 <div style={{
6 display: 'block',
7 width: '100%',
8 background: type === 'success' ? 'rgba(0, 255, 0, 0.2)' : 'rgba(255, 0, 0, 0.2)',
9 color: 'black',
10 padding: '1rem',
11 margin: '0.5rem',
12 borderRadius: '10px',
13 boxShadow: '0px 4px 10px rgba(0,0,0,0.1)'
14 }}>
15 {message ? message : ('The World Needs more `Lerts')}
16 </div>
17 )
18}
19 
20const ContactUs = () => {
21 const [contactName, setContactName] = useState('')
22 const [contactEmail, setContactEmail] = useState('')
23 const [honey, setHoney] = useState('')
24 
25 /**
26 * The error message variable and function
27 */
28 const [alertBanner, setAlertBanner] = useState(null)
29 
30 function handleForm(e) {
31 e.preventDefault()
32 
33 if (honey.length >= 1) {
34 return
35 }
36 
37 let body = {
38 name: contactName,
39 email: contactEmail,
40 website: honey,
41 }
42 
43 fetch(
44 `${location.origin}/api/contactus`,
45 {
46 method: 'POST',
47 body: JSON.stringify(body)
48 }
49 )
50 .then(response => {
51 
52 if (response.status >= 300) {
53 setAlertBanner({
54 message: response.statusText,
55 type: 'error'
56 })
57 
58 return;
59 }
60 
61 setAlertBanner({
62 message: response.statusText,
63 type: 'success'
64 })
65 
66 console.debug('response')
67 console.debug(response);
68 })
69 .catch(error => {
70 
71 setAlertBanner({
72 message: response.statusText,
73 type: 'error'
74 });
75 
76 console.debug('error')
77 console.error(error)
78 })
79 }
80 
81 return (
82 <>
83 <form onSubmit={handleForm} id="contactUsForm">
84 {/* The Alert Box for the error message */}
85 {alertBanner !== null ? <Alert { ...alertBanner } /> : null}
86 
87 <div style={{ marginBottom: '0.75rem', display: 'flex', flexDirection: 'column' }}>
88 <label htmlFor="name">Name</label>
89 <input
90 name="name"
91 id="name"
92 value={contactName}
93 onChange={e => setContactName(e.target.value)}
94 placeholder="Your Name"
95 type="text"
96 />
97 </div>
98 <div style={{ marginBottom: '0.75rem', display: 'flex', flexDirection: 'column' }}>
99 <label htmlFor="email">Email</label>
100 <input
101 name="email"
102 id="email"
103 value={contactEmail}
104 onChange={e => setContactEmail(e.target.value)}
105 placeholder="Your email"
106 type="email"
107 />
108 </div>
109 
110 <input
111 style={{ display: 'none' }}
112 name="website"
113 value={honey}
114 onChange={e => setHoney(e.target.value)}
115 />
116 
117 <button htmlFor="contactUsForm" type="submit">Submit</button>
118 </form>
119 </>
120 )
121}
122 
123export default ContactUs;

You can then use this component in a page with by importing the file and then using the <ContactUs /> component.

An example could be in the index page, it would like like this now:

1import Head from 'next/head'
2import styles from '../styles/Home.module.css'
3import ContactUs from '../components/ContactUs'
4 
5export default function Home() {
6 return (
7 <div className={styles.container}>
8 <Head>
9 <title>Create Next App</title>
10 <link rel="icon" href="/favicon.ico" />
11 </Head>
12 
13 <main className={styles.main}>
14 <h1 className={styles.title}>
15 Welcome to <a href="https://nextjs.org">Next.js!</a>
16 </h1>
17 
18 <p className={styles.description}>
19 This is an example contact page
20 </p>
21 
22 {/* Delete the grid area of the index page and place the component there. */}
23 <ContactUs />
24 </main>
25 
26 <footer className={styles.footer}>
27 <a
28 href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
29 target="_blank"
30 rel="noopener noreferrer"
31 >
32 Powered by{' '}
33 <img src="/vercel.svg" alt="Vercel Logo" className={styles.logo} />
34 </a>
35 </footer>
36 </div>
37 )
38}

Create An ENV file for local development

To be able to change the environment variables for your local Next.js app, you can create a .env.local file in the root directory. In that you can place the APP_URL and the APP_TOKEN that you need to use in the actual app.

So you would have the following in the file:

1# .env.local
2 
3APP_URL="http://localhost:8000"
4APP_TOKEN="random_token_that_is_really_long_but_not_short"

4. Trying the system out

Now that you have built all those parts, you should have a file structure that looks similar to the below example:

1.
2├── components/
+│ └── ContactUs.js [New]
4└── pages/
5 ├── api/
+ │ └── contactus.js [New]
7 └── index.js [Edited]

We now have a Next.js application with a the form, an API endpoint and the token that you generated in Part 1, now we are going to boot both apps up and test them out.

You can start either of them first, so for this we can run npm run dev or yarn dev as we are in this project already, then go to the Laravel one and run php artisan serve. Also for the Laravel instance you can start up Mailhog or have Mailtrap running.

You can visit each one to make sure they are running.

Local setup for a static form with Vercel

To summarize what is needed to get a version of this running in your local site working, you would need the following basically:

Production / Deployed static form

When you are happy with the changes you have made to the code, you can go about the following for making these available in a live environment other than your computer

Syntax highlighting by Torchlight.