---
title: Build a Next.js App Easily Using ApyHub APIs
url: https://apyhub.com/blog/how-to-build-a-nextjs-app-with-apyhub
author: Edijs Musajevs
published: 2023-02-10T00:00:00Z
tags: [engineering]
---

# Build a Next.js App Easily Using ApyHub APIs

# Build a Next.js App Easily Using ApyHub APIs

## Introduction

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

***

## Prerequisites

Before starting, make sure you have:

* Basic knowledge of Next.js and TypeScript
* Node.js v16+
* An ApyHub account

***

## Setting 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

```bash
git clone -b starter https://github.com/apyhub/with-nextjs.git
```

### 2. Navigate Into the Project

```bash
cd with-nextjs
```

### 3. Install Dependencies

```bash
npm install
```

### 4. Start the Development Server

```bash
npm run dev
```

Your app should now be running locally.

***

## Set Up Your ApyHub Account

Go to [ApyHub](https://apyhub.com/signup) and create an account or log in.

Once logged in, access the following APIs:

* [Timezone API](https://apyhub.com/utility/data-lists-timezone)
* [iCal Generator API](https://apyhub.com/utility/generator-ical)

### 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:

```text
with-nextjs
```

#### 3. 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.

***

## Integrate ApyHub With a Next.js Project

### Install the ApyHub Library

Install the `apyhub` Node.js library:

```bash
npm install apyhub
```

### Create the Environment File

Create a `.env.local` file in the root of your project:

```text
APY_TOKEN=YOUR_APP_TOKEN_GOES_HERE
```

Replace `YOUR_APP_TOKEN_GOES_HERE` with your actual ApyHub token.

***

## Initialize the ApyHub Client

Create a new folder called `lib`:

```text
lib/
```

Inside the `lib` folder, create:

```text
apyhub.ts
```

Add the following code:

```typescript
import { initApyhub } from "apyhub";

const apy = initApyhub(process.env.APY_TOKEN as string);

export { apy };
```

***

## How 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:

```text
Browser
   ↓
Next.js Server
   ↓
ApyHub API
   ↓
Next.js Server
   ↓
Browser
```

***

## Using `getServerSideProps`

Inside:

```text
/pages/index.tsx
```

Next.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:

```typescript
import { initApyhub, data } from "apyhub";

const apy = initApyhub(process.env.APY_TOKEN as string);

export { apy, data };
```

### Fetch the Timezones

Inside:

```text
/pages/index.tsx
```

Use `getServerSideProps`:

```typescript
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.

***

## Fetching 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:

```text
/pages/api/
```

Then create:

```text
/pages/api/ical.ts
```

Your project structure should look similar to:

```text
with-nextjs/
├── lib/
│   └── apyhub.ts
├── pages/
│   ├── api/
│   │   └── ical.ts
│   └── index.tsx
├── .env.local
├── package.json
└── ...
```

***

## Add the iCal Generator

We will use the `generate` object from the ApyHub library to create the iCal file.

Update:

```text
/lib/apyhub.ts
```

to:

```typescript
import { initApyhub, data, generate } from "apyhub";

const apy = initApyhub(process.env.APY_TOKEN as string);

export { apy, data, generate };
```

***

## Create the iCal API Handler

Inside:

```text
/pages/api/ical.ts
```

Create a handler function:

```typescript
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;
```

***

## How the iCal Request Works

The frontend sends the event information to:

```text
/api/ical
```

The Next.js API route then:

1. Receives the request.
2. Extracts the event information.
3. Calls `generate.ical()`.
4. Sends the request to ApyHub.
5. Receives a URL for the generated iCal file.
6. Returns the URL to the browser.

The overall flow is:

```text
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 File
```

***

## Testing the Application

Fill out the event form in your application and click:

```text
Create Event
```

The browser will make a request to:

```text
/api/ical
```

The 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:

```typescript
window.open(data, "_blank");
```

***

## Deployment

Now that the application is complete, you can deploy it to Vercel.

Follow the [Next.js deployment guide](https://nextjs.org/learn/basics/deploying-nextjs-app/deploy).

### Environment Variables

When deploying the application, make sure to add:

```text
APY_TOKEN=YOUR_APP_TOKEN_GOES_HERE
```

to your Vercel environment variables.

> **Important:** Do not commit `.env.local` or your API token to Git.

***

## Bonus: 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**:

[DNS Email Validator](https://apyhub.com/utility/validator-dns-email)

You can call this API from:

```text
/pages/api/ical.ts
```

before generating the iCal file.

The flow would become:

```text
User submits event
        ↓
Validate email addresses
        ↓
Are emails valid?
     ↙       ↘
   No         Yes
   ↓           ↓
Return      Generate
Error       iCal file
               ↓
          Return URL
```

This ensures that the organizer and attendee email addresses contain valid domains before generating the event.

***

## Final Project Structure

After completing the tutorial, your project can look like this:

```text
with-nextjs/
│
├── lib/
│   └── apyhub.ts
│
├── pages/
│   ├── api/
│   │   └── ical.ts
│   │
│   └── index.tsx
│
├── public/
│
├── .env.local
├── package.json
├── tsconfig.json
└── ...
```

***

## Technologies Used

* **Next.js**
* **TypeScript**
* **ApyHub APIs**
* **Node.js**
* **REST APIs**
* **Server-Side Rendering**
* **Next.js API Routes**
* **iCal**
* **Vercel**

***

## Key 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
