Welcome folks today in this blog post we will be saving the html form
data into google sheets
using next.js. For building this application we will need these following packages which are as follows
react-hook-form
is a special package which takes care of the information inside the html form. It contains handy methods to work with html input fields with the help of react hooks.
googleapis
is a special package which will connect the google sheets api inside our next.js project
Getting the Credentials
Now guys first of all go to google developer console account and get the credentials
needed for this application. So first of all enable the google sheets api as shown below
And now you need to create the service account for this project as shown below
Just select json
and download this file securely inside your system and copy paste this file inside the same directory of your next.js project
Now make a env
file to store the below details from the secret.json
file that you previously downloaded
1 2 3 |
CLIENT_EMAIL=###yourclientemail### CLIENT_ID=###yourclientid### PRIVATE_KEY=###yourprivatekey### |
Here you need to replace the client_email
, client_id
and private_key
from the secret.json file
Creating the HTML5 Form
Now we will create the html5
form to collect user data. Inside this form we will collect two information such as name
of the user and feedback
data
Now inside the pages
directory we have the index.js
file
pages/index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
import Head from 'next/head'; import { useForm } from 'react-hook-form'; export default function Home() { const { register, handleSubmit, reset, formState: { errors }, // catch error messages } = useForm(); function submitHandler(data) { console.log(data) } return ( <div className={styles.container}> <Head> <title>Create Next App</title> </Head> <main> <h1> Your response matters </h1> <form onSubmit={handleSubmit(submitHandler)}> <input type="text" placeholder="Enter Name" {...register('Name', { required: 'Please enter your name' })} /> {errors.Name && errors.Name.message} <input type="text" placeholder="Enter Message" {...register('Feedback', { required: 'Enter your feedback!' })} /> {errors.Feedback && errors.Feedback.message} <button type="submit" variant="ghost" > Submit Form </button> </form> </main> </div> ); } |
So you can see that we have two input fields
name and feedback. We have also included the react-hook-form
library
And now after that we will be making a fetch
request to the google sheet api as shown below
1 2 3 4 5 6 7 8 9 10 11 |
function submitHandler(data) { console.log(data) fetch('/api/sheet', { method: 'POST', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json', }, }); reset(); // clears the input on submitting } |
As you can see that we are using the fetch
request and inside this request we are passing the name
and feedback and then we are converting it to json string
and then we are resetting the input fields after you submit the form
And now guys we will making the api
route for handling this user form.
So inside the pages
folder and we have api
folder we have sheet.js
file
pages/api/sheet.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import { google } from 'googleapis'; async function handler(req, res) { if (req.method === 'POST') { const { Name, Feedback } = req.body; console.log(Name, Feedback); const auth = new google.auth.GoogleAuth({ credentials: { client_email: process.env.CLIENT_EMAIL, client_id: process.env.CLIENT_ID, private_key: process.env.PRIVATE_KEY.replace(/\\n/g, '\n'), }, scopes: [ 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/spreadsheets', ], }); const sheets = google.sheets({ auth, version: 'v4', }); const response = await sheets.spreadsheets.values.append({ spreadsheetId: "1sB58UkzihWdRyJBjYRzKCcLSd6d--PlH3NV8kaiPQQA", range: 'Sheet1!A2:C', valueInputOption: 'USER_ENTERED', requestBody: { values: [[Name,Feedback]], }, }); res.status(201).json({ message: 'It works!', response }); } res.status(200).json({ message: 'Hey!' }); } export default handler; |
In this block of code guys you need to replace the google sheet
id. We are importing the googleapis and then using the methods and scopes to grant permission for inserting the data to google sheets.
Grant Permission in Google Sheets
Now guys we need to allow the permission of google sheets
by allowing the email address as shown below
Now if you run the next.js
app by executing the below command
npm run dev