API Routes
API routes great build-in feature of Next.js.
If you need to talk to an external API, fetch data or modify data in the database, API route is the way to go.
export default (req, res) => {
res.statusCode = 200
res.json({ name: 'John Doe' })
}
Above is the default Hello API route. If you visit http://localhost:3000/api/hello
in your browser, you would see the response from this endpoint.
Subscribe API Overview
Here is a quick overview of the remaining API work:
- send user
email input
from the UI - create subscribe API endpoint -
/api/subscribe.js
- subscribe API will get
CONVERTKIT_API_URL
,CONVERTKIT_API_KEY
andCONVERTKIT_FORM_ID
fromenv variables
- send request to ConvertKit API
- return
status 201
if everything goes well - return
status 400
or500
if something goes wrong
- return
- Update UI accordingly
- While the request is pending we want to toggle the
isLoading
variable totrue
to update our UI. - When the request is completed we either show a success message and error message.
- While the request is pending we want to toggle the
Send request on form submit
When we submit a valid form, we will create a new fetch
request and pass the email
value in the query
.
// src/components/SignupForm.js
const subscribe = async ({ email }) => {
const res = await fetch(`/api/subscribe?email=${email}`);
};
// handle form submit
const onSubmit = (data) => subscribe(data);
The subscribe
needs to be async/await
because we need to wait for the response
from the backend API.
Create Subscribe Endpoint
// src/pages/api/subscribe.js
export default (req, res) => {
const { email, tags } = req.query;
if (!email) {
return res.status(400).json({ error: "Email is required" });
}
// Part 2 continue
};
Firstly we check if the email
is included in the request query. If it is not included, we will return "Email is required"
error.
In the next unit we will implement the response from ConvertKit API.