Build a Next.js App Easily Using ApyHub APIs
01Introduction
This tutorial will guide you through the steps of setting up a Next.js app and integrating it with ApyHub.
We will use the following ApyHub APIs:
- Timezone API
- iCal API
02Prerequisites
Before starting, make sure you have:
- Basic knowledge of Next.js and TypeScript
- Node.js v16+
- An ApyHub account
03Setting Up the Next.js Project
Open your terminal and navigate to the directory where you want to set up your project.
1. Clone the Next.js Starter Project
git clone -b starter https://github.com/apyhub/with-nextjs.git2. Navigate Into the Project
cd with-nextjs3. Install Dependencies
npm install4. Start the Development Server
npm run devYour app should now be running locally.
04Set Up Your ApyHub Account
Go to ApyHub and create an account or log in.
Once logged in, access the following APIs:
Create an ApyHub API Token
To communicate with the APIs from your Next.js application, you need an APY_TOKEN environment variable.
1. Create an App
On the API documentation page, click the Create App button in the top-right corner.
2. Create a Token
Create a new token with the name:
with-nextjs3. Copy the Token
After creating the token, you can view it on the My Apps page.
Copy the token and store it securely. We will use it in the Next.js project.
Important: Never expose your API token in client-side code.
05Integrate ApyHub With a Next.js Project
Install the ApyHub Library
Install the apyhub Node.js library:
npm install apyhubCreate the Environment File
Create a .env.local file in the root of your project:
APY_TOKEN=YOUR_APP_TOKEN_GOES_HEREReplace YOUR_APP_TOKEN_GOES_HERE with your actual ApyHub token.
06Initialize the ApyHub Client
Create a new folder called lib:
lib/Inside the lib folder, create:
apyhub.tsAdd the following code:
import { initApyhub } from "apyhub";
const apy = initApyhub(process.env.APY_TOKEN as string);
export { apy };07How to Use ApyHub API Utilities
Fetching Timezones
Our UI currently has an empty dropdown menu for time zones.
Instead of manually creating an array of time zones, we can use the ApyHub Timezone API.
Why Server-Side Requests?
ApyHub does not support client-side API requests because doing so could expose your API credentials.
If you attempt to make the API request directly from the browser, you may encounter a CORS error.
Therefore, we will use Next.js as a bridge between the frontend and backend.
The flow looks like this:
Browser
↓
Next.js Server
↓
ApyHub API
↓
Next.js Server
↓
Browser08Using getServerSideProps
Inside:
/pages/index.tsxNext.js provides the getServerSideProps function for executing server-side code.
We currently return an empty array for the time zones.
Let's replace it by fetching the time zones from ApyHub.
Update lib/apyhub.ts
Import and export the data object:
import { initApyhub, data } from "apyhub";
const apy = initApyhub(process.env.APY_TOKEN as string);
export { apy, data };Fetch the Timezones
Inside:
/pages/index.tsxUse getServerSideProps:
import { data } from "../lib/apyhub";
export const getServerSideProps = async () => {
const { data: timezones } = await data.timezones();
return {
props: {
timezones,
},
};
};Reload the page.
The timezone dropdown should now contain the available time zones from ApyHub.
09Fetching an iCal File
Now that users can select a time zone from the dropdown, we have the necessary information to generate an iCal event.
We will use a Next.js API Route to handle the request.
Create the API Route
Inside the pages directory, create an api folder:
/pages/api/Then create:
/pages/api/ical.tsYour project structure should look similar to:
with-nextjs/
├── lib/
│ └── apyhub.ts
├── pages/
│ ├── api/
│ │ └── ical.ts
│ └── index.tsx
├── .env.local
├── package.json
└── ...10Add the iCal Generator
We will use the generate object from the ApyHub library to create the iCal file.
Update:
/lib/apyhub.tsto:
import { initApyhub, data, generate } from "apyhub";
const apy = initApyhub(process.env.APY_TOKEN as string);
export { apy, data, generate };11Create the iCal API Handler
Inside:
/pages/api/ical.tsCreate a handler function:
import { generate } from "../../lib/apyhub";
import { NextApiRequest, NextApiResponse } from "next";
const handler = async (
req: NextApiRequest,
res: NextApiResponse
) => {
const {
summary,
description,
organizer_email,
attendees_emails,
location,
timezone,
start_time,
end_time,
meeting_date,
recurring,
recurrence,
} = req.body;
const url = await generate.ical({
summary,
description,
organizerEmail: organizer_email,
attendeesEmails: attendees_emails,
location,
timeZone: timezone,
startTime: start_time,
endTime: end_time,
meetingDate: meeting_date,
recurring,
recurrence,
responseFormat: "url",
});
return res.status(200).json(url);
};
export default handler;12How the iCal Request Works
The frontend sends the event information to:
/api/icalThe Next.js API route then:
- Receives the request.
- Extracts the event information.
- Calls
generate.ical(). - Sends the request to ApyHub.
- Receives a URL for the generated iCal file.
- Returns the URL to the browser.
The overall flow is:
Frontend
│
│ POST /api/ical
▼
Next.js API Route
│
│ generate.ical()
▼
ApyHub API
│
│ iCal URL
▼
Next.js API Route
│
│ JSON response
▼
Frontend
│
│ window.open(data, "_blank")
▼
iCal File13Testing the Application
Fill out the event form in your application and click:
Create EventThe browser will make a request to:
/api/icalThe API route sends the request to ApyHub to generate the iCal file.
ApyHub returns a URL pointing to the generated file.
The URL is then returned to the browser.
The frontend can open the generated file using:
window.open(data, "_blank");14Deployment
Now that the application is complete, you can deploy it to Vercel.
Follow the Next.js deployment guide.
Environment Variables
When deploying the application, make sure to add:
APY_TOKEN=YOUR_APP_TOKEN_GOES_HEREto your Vercel environment variables.
Important: Do not commit
.env.localor your API token to Git.
15Bonus: Validate Email Addresses
Currently, there is no validation to check whether the organizer or attendee email addresses have valid domains.
To improve the application, you can use the ApyHub DNS Email Validator API:
You can call this API from:
/pages/api/ical.tsbefore generating the iCal file.
The flow would become:
User submits event
↓
Validate email addresses
↓
Are emails valid?
↙ ↘
No Yes
↓ ↓
Return Generate
Error iCal file
↓
Return URLThis ensures that the organizer and attendee email addresses contain valid domains before generating the event.
16Final Project Structure
After completing the tutorial, your project can look like this:
with-nextjs/
│
├── lib/
│ └── apyhub.ts
│
├── pages/
│ ├── api/
│ │ └── ical.ts
│ │
│ └── index.tsx
│
├── public/
│
├── .env.local
├── package.json
├── tsconfig.json
└── ...17Technologies Used
- Next.js
- TypeScript
- ApyHub APIs
- Node.js
- REST APIs
- Server-Side Rendering
- Next.js API Routes
- iCal
- Vercel
18Key Concepts Learned
By completing this tutorial, you learn how to:
- Create a Next.js application
- Install and use an external Node.js API library
- Store API credentials using environment variables
- Make secure server-side API requests
- Use
getServerSideProps - Create Next.js API routes
- Generate iCal files through an external API
- Handle API responses
- Deploy a Next.js application to Vercel
- Validate email domains before processing requests
