Max Next – Section 8 – Adding Backend Code With API Routes (FullStack React)


Courses

Updated Jul 15th, 2021

Table of Contents

Chapter Details

Chapter 136. Module Introduction

Chapter 137. What are “API Routes”?

Sometime we want to do more than just serve html pages, accept user feedback submission, newsletter signups, etc.

What happens behind the scenes?

Send data to the database and then receive a response.

Get data, using data, sending back data.

API routes are about URLs that don’t return pages (html) but instead provide a (REST) API

NextJS allows us to build an API right from within our app.

Requests are typically not sent by entering a URL in the browser but via JavaScript code (AJAX using fetch or axios)

Chapter 138. Writing Our First API Route

Create an API subfolder folder in pages folder that must be called “api” and inside you can added pages the same you would before that creates special path.

Inside the files we don’t export a react component. Instead we create a function, typically called handler that takes a req, and response. This function we export as default.

Inside this handler function we can handle get request and post request and really any method request.

We write server side node code in this function, node code that has been enhance by the NextJS team to look like ExpressJS.

Res.status(200).json({whatEvsMessage: “This Works!”})

If you navigate to the URL in the browser, (which we wouldn’t typically do We would access via a fetch function), We can then go to the network tab in the chrome developer tools and under the headers tab we see the response data, some metadata for the response, content-type of application JSON

Chapter 139. Preparing the Frontend Form

Dummy form added without styling. We accept email address and user feedback and then sent to database. We don’t want to connect to a database from the front-end. We send the data to the API route ad then in the route we can safely connect to the database. Uses useRef to connect to the input and a submitFormHandler function.

import {useRef} from 'react'

function HomePage() {
  const emailInputRef = useRef()
  const feedbackInputRef = useRef()

  function submitFormHandler(event) {
    event.preventDefault
    const enteredEmail = emailInputRef.current.value
    const enteredFeedback = feedbackInputRef.current.value
    // skip validation for now
    // send http POST request with fetch()
  }

return (
  <div>
  <h1>The Home Page</h1>
  <form onSubmit={submitFormHandler}>
    <div>
    <label htmlFor="email">Your Email Address</label>
    <input type="email" id="email" ref={emailInputRef}></input>
    </div>
    <div>
    <label htmlFor="feedback">Your Feedback</label>
    <textarea id="feedback" rows="5" ref={feedbackInputRef}></textarea>
    </div>
   <button>Send Feedback</button>
  </form>
  </div>
)
}

export default HomePage

Chapter 140. Parsing The Incoming Request & Executing Server-side Code

In the API handler function use and if check to make sure the incoming request is a POST request and if so, extract data using req.body. Add a feedback.json file to a data folder in your project’s root directory. Goal is to open the file and store it in their when the request comes in using the “fs” and “path” modules.

Good chapter to re-watch

Chapter 141. Sending Requests To API Routes

In the front-end use the fetch function to send a request to /api/feedback and configure to send as a POST request and a body object and some headers object with with a key of ‘Content-Type’ set to “application/json.” We are now able to work with user-submitted data which allows us to add more features to our application.

Chapter 142. Using API Routes To Get Data

Can also handle incoming get requests however you want to say get data from a file and send that back as a response to display on the page. Create a Load Feedback button that sends a fetch get request. Set some state for feedback items and then maps through them to send as json.

Chapter 143. Using API Routes For Pre-Rendering Pages

We want a non-API /feedback route that display the data. Get feedback items and maps into list items. For internal API routes you should not use fetch inside of “getStaticProps” or “getServerSideProps” to talk to your own API. Instead, write the node.js logic code directly in these functions. Export the functions from your API file and then import them into your new page component. Leverage the fact the API and the Application is running on the same server.

Chapter 144. Creating & Using Dynamic API Routes

Let’s say you want to support /api/feedback/feedbackId to show details for a single feedback item. We use the similar bracket syntax for dynamic API routes. Create a [feedbackId].js file in the “api” folder on the same level as the “feedback.js” file.

Need to re-watch this video

Chapter 145. Exploring Different Ways Of Structuring API Route Files

Can have catch all dynamic API routes by adding three dots inside of brackets before name. Also important to know how NextJS prioritizes API files, will use more specific file. Flexibility similar to non-API files and folder structuring.

Chapter 146. Module Summary

Another useful feature you will not need in every site but if you do it is nice to have the ability to build an API directly in the same project.

Chapter 147. Module Resources