ServiceTitan Integrations with Next.js: Custom Solutions for Streamlined Operations
by Spencer, Co-Founder / CTO
Introduction
In the service industry, companies like HVAC, electrical, and plumbing businesses often rely on ServiceTitan for operational management. However, many find that customization is essential to align ServiceTitan’s capabilities with their unique business goals. ServiceTitan integrations can bridge this gap by connecting the platform to other essential tools, simplifying complex workflows, and eliminating redundant manual tasks.
Why ServiceTitan Integrations Are Essential for Service Businesses
Custom ServiceTitan integrations enable companies to reshape daily operations, improve data accessibility, and eliminate inefficiencies. Some of these key benefits include:
- Optimized Scheduling: Custom integrations allow you to automate and streamline scheduling processes, reducing manual intervention and aligning with real-time availability.
- Enhanced Customer Data Management: Connect ServiceTitan to other systems to centralize customer information, giving teams consistent access to accurate data.
- Enriched Marketing: ServiceTitan integrations automate customer data syncing with marketing tools, enabling targeted, data-driven campaigns that increase engagement and drive repeat business.
- Reduced Operational Friction: Integrating ServiceTitan with tools like Next.js supports real-time data flow, allowing businesses to optimize operational workflows to their specific needs.
With custom integrations, ServiceTitan can evolve from a general tool into a powerful solution tailored to your specific workflows, enhancing team productivity and improving customer experience.
What You'll Learn
In this guide, we’ll walk through a custom integration that uses Next.js to connect to ServiceTitan’s API. This integration will help you build a custom booking form, leveraging ServiceTitan’s capabilities to improve scheduling and customer data management. By following these steps, you’ll gain the skills to create flexible, efficient workflows tailored to your service business.
Here's what we'll be doing in this tutorial:
- Setting Up a Next.js Application: Lay the groundwork for your custom integration.
- Building a Custom Booking Form: Collect essential customer information with a user-friendly interface.
- Connecting to ServiceTitan's API: Authenticate and interact with ServiceTitan programmatically.
- Implementing Best Practices: Ensure your integration is secure, efficient, and scalable.
At Aclarify, we specialize in custom integrations that make software like ServiceTitan work harder for your business.
Ready to build your custom integration? Let's get started!
Prerequisites
Before diving into the tutorial, let's make sure you have everything in place to follow along smoothly.
Technical Knowledge
This guide assumes you're comfortable with the following:
- JavaScript and React: Understanding of components, state management, and JSX.
- Next.js Framework: Familiarity with Next.js features like pages, components, and routing.
- RESTful APIs: Experience with making HTTP requests and handling responses.
Development Environment
Ensure your development environment is set up with the following tools:
-
Node.js and npm: Download and install Node.js, which includes npm.
-
Code Editor: We recommend Visual Studio Code with extensions for React and TypeScript.
-
ServiceTitan API Credentials: You'll need access to the following ServiceTitan API credentials:
SERVICE_TITAN_CLIENT_ID
SERVICE_TITAN_CLIENT_SECRET
SERVICE_TITAN_APP_KEY
SERVICE_TITAN_TENANT_ID
SERVICE_TITAN_BOOKING_PROVIDER_ID
Need Help Obtaining Your Credentials?
If you're unsure how to get these credentials, log in to your ServiceTitan account or reach out to their support team for assistance.
With everything prepared, you're all set to begin building your custom integration!
Project Setup
To kickstart our integration, we'll set up the initial Next.js application and prepare our development environment.
Cloning the Repository
We've prepared a companion repository that contains the base code for this tutorial. This repository is structured to guide you through each phase of the integration.
Key Github Repository Link...
You can find the GitHub Repository ➡️ here ⬅️
Steps to Clone the Repository
-
Clone the Repository
Open your terminal and run:
-
Navigate to the Project Directory
Installing Dependencies
With the repository cloned, let's install the necessary dependencies and start the development server.
-
Install Dependencies: Run the following command in your terminal:
-
Start the Development Server: Start the development server with:
-
View the Application: Open your browser and navigate to http://localhost:3000. You should see the default Next.js welcome page.
Understanding the Repository Structure
Before we start building our booking integration, let's familiarize ourselves with the project's structure and how we'll navigate through the tutorial phases.
Project Overview
Our application is built with:
- Next.js: For server-side rendering and routing.
- TypeScript: For type safety and an improved developer experience.
- Tailwind CSS: For utility-first CSS styling.
Directory Structure
Here's a simplified view of the project's directory structure at the initial phase:
Key Files Explained:
src/app/page.tsx
: The main page component where we'll build the booking form.
Navigating Tutorial Phases
Each phase of the tutorial corresponds to a branch in the repository. This allows you to:
- Follow Along Incrementally: Start at the initial phase and build upon it by following the tutorial instructions.
- Check Your Work: After completing a phase, you can compare your code with the corresponding branch.
Phase Branches Overview
To help you navigate through each phase of the tutorial, we've organized the project repository into the following branches:
Branch Name | Description |
---|---|
phase/0-initial-boilerplate | Contains the initial boilerplate setup for the Next.js application. |
phase/1-ui-form-scaffolding | Implements the user interface for the booking form. |
phase/2-create-booking-api | Sets up the backend API for handling booking submissions. |
phase/3-connect-booking-ui-to-api | Connects the frontend booking form to the backend API. |
phase/complete-implementation | Finalizes the integration and includes all completed features. |
Each branch corresponds to a specific stage in the development process, allowing you to follow along step-by-step:
-
phase/0-initial-boilerplate
: Start here to begin building the user interface for the booking form. This tutorial phase involves creating React components, styling the form using Tailwind CSS, and ensuring the form is responsive and user-friendly. -
phase/1-ui-form-scaffolding
: This branch guides you through setting up the backend API that will handle form submissions. You'll learn how to create server-side actions in Next.js, define TypeScript types for form data, and implement secure API endpoints to process and store booking information. -
phase/2-create-booking-api
: In this phase, you'll connect your frontend booking form to the backend API. This involves handling form submissions, managing application state, and ensuring that data flows seamlessly from the UI to the server, with appropriate error handling and user feedback. -
phase/3-connect-booking-ui-to-api
: Finally, move to this branch to finalize the integration and polish your application. This includes adding additional features, optimizing performance, implementing authentication if necessary, and conducting thorough testing to ensure everything works as intended. -
phase/complete-implementation
: This branch contains our fully implemented custom Booking application.
By following the branches in order, you can incrementally build and verify each component of your custom integration, ensuring a smooth and organized development experience. Each branch builds upon the previous one, allowing you to track progress and understand how each part contributes to the final implementation.
How to Switch Between Phases
-
Start at Phase 0: Ensure you're on the initial branch:
-
Switch to the Next Phase: After completing a phase, switch to the next branch to compare your code:
-
Repeat for Subsequent Phases: Continue this process for each phase of the tutorial.
Preparing for the Integration
Now that you're familiar with the project structure and how to navigate the tutorial, we're ready to begin building our custom booking integration.
Aclarify's Advice
Having a clear understanding of the project setup will make the development process smoother. If you encounter any issues, revisiting this section can help resolve setup-related problems.
Building the Booking Form UI Scaffold
With our project set up and running, it's time to build the user interface for our booking form. This form will capture essential customer information needed to create a booking in ServiceTitan.
Step 1: Cleaning Up the Home Page
First, let's replace the default Next.js content with our booking form component.
Modify page.tsx
Open src/app/page.tsx
and replace its content with the following code:
Explanation:
- Lines 1-3: We import the
BookingForm
component, which we'll create next, and define theBookingPortal
component. - Lines 6-24: We set up the page layout with Tailwind CSS classes for styling, including a background gradient and centered text.
- Lines 25-31: We add a header and a description to introduce the booking form to users.
- Line 33: We include the
<BookingForm />
component, which will render our booking form.
Step 2: Creating the Booking Form Component
Next, we'll create the BookingForm
component that will contain our form fields.
Create the components
Directory
In the src
directory, create a new folder called components
:
Create BookingForm.tsx
Inside src/components/
, create a new file named BookingForm.tsx
and add the following code:
Explanation:
- Lines 6-66: We define
formFields
, an object mapping each form field to its properties. This will be used to dynamically render input fields. - Lines 70-80: The
BookingForm
component renders a<form>
element containing the input fields and a submit button.
Step 3: Creating the Input Component
We'll create a reusable Input
component to render each form field.
Create Input.tsx
Inside src/components/
, create a new file named Input.tsx
and add the following code:
Explanation:
- Lines 4-6: We define the
InputProps
type, extending standard input attributes and adding alabel
prop. - Lines 16-32: The
Input
component renders a<label>
and an<input>
element with appropriate styling and props.
Step 4: Creating the Submit Button Component
Next, we'll create a SubmitButton
component for form submission.
Create SubmitButton.tsx
Inside src/components/
, create a new file named SubmitButton.tsx
and add the following code:
Explanation:
- Lines 4-9: The
SubmitButton
component renders a styled<button>
element for form submission.
Step 5: Defining TypeScript Types
We'll define the types for our booking form data.
Create booking.type.ts
Create a new directory src/lib/types/
and inside it, create a file named booking.type.ts
with the following content:
Explanation:
- We define the
CreateBookingFormDto
type, which represents the structure of our booking form data.
Step 6: Testing the Form
Now that we've set up all the components, your application should display the booking form when you navigate to http://localhost:3000.
Visual Check:
Keep in mind...
At this point, the form doesn't have any functionality; we'll handle form submission and integrate with the API in the next sections.
Creating the Backend API for Booking
With the frontend form in place, it's time to create the backend API that will handle booking submissions. This API will process the form data and communicate with ServiceTitan's API to create a booking.
Step 1: Setting Up the Booking Action
We'll create a server-side action in Next.js to process the booking form data securely.
Create createBooking.action.ts
Create a new directory src/lib/actions/
and inside it, create a file named createBooking.action.ts
with the following content:
Explanation:
- Lines 15-34: Loops through required fields, extracts, and validates form data from the
FormData
object. - Lines 37-54: Transforms the inbound form data into the structure required by ServiceTitan's API.
- Lines 57-61: Uses the
makeRequest
utility to send a POST request to ServiceTitan's API to create a booking. - Lines 68-76: Catches and logs any errors, returning a meaningful message to the client.
Step 2: Configuring ServiceTitan Settings
We'll create a configuration file to manage our ServiceTitan credentials and settings securely.
Create serviceTitan.config.ts
Create a new directory src/lib/config/
and inside it, create a file named serviceTitan.config.ts
with the following content:
Explanation:
- Lines 2-18: An immediately invoked function expression (IIFE) checks for the presence of required environment variables. If any are missing, it throws an error to prevent the application from running without necessary credentials.
- Lines 20-26: Exports a configuration object containing all ServiceTitan-related credentials, ensuring they are accessible throughout the application.
Step 3: Defining TypeScript Types for Outbound Data
We need to define the structure of the data we'll send to ServiceTitan's API.
Update booking.type.ts
Inside src/lib/types/
, update the existing booking.type.ts
file or create it if it doesn't exist, and add the following content:
Explanation:
- Lines 2-8: Defines the structure for address information.
- Lines 10-13: Defines the structure for contact information, specifying the type of contact (Phone or Email).
- Lines 15-23: Represents the data structure required by ServiceTitan's API to create a booking.
Step 4: Creating Utility Functions for Authentication and API Requests
We'll create utility functions to handle authentication with ServiceTitan and make API requests.
Create authenticateST.util.ts
Create a new directory src/lib/utils/
and inside it, create a file named authenticateST.util.ts
with the following content:
Explanation:
authenticateServiceTitan
Function: Authenticates with ServiceTitan's API using client credentials and retrieves an access token.- Lines 5-15: Sends a POST request to the authentication endpoint with required credentials.
- Lines 17-21: Logs and throws an error if authentication fails.
- Line 24: Returns the access token upon successful authentication.
Create makeSTRequest.util.ts
Inside src/lib/utils/
, create a file named makeSTRequest.util.ts
with the following content:
Explanation:
makeRequest
Function: A generic function to make authenticated API requests to ServiceTitan.- Line 14: Retrieves an access token using
authenticateServiceTitan
. - Lines 20-24: Sets up headers with the access token and app key, and includes the request body if provided.
- Lines 28-34: Logs and throws an error if the API request fails.
- Line 37: Returns the parsed JSON response from the API.
- Line 14: Retrieves an access token using
Step 5: Adding Environment Variables
Ensure you have the required environment variables set up in your .env.local
file at the root of your project:
Explanation:
.env.local
File: Stores sensitive information like API keys and secrets. Ensure this file is included in your.gitignore
to prevent it from being committed to version control.- Variables Required:
SERVICE_TITAN_APP_KEY
SERVICE_TITAN_TENANT_ID
SERVICE_TITAN_BOOKING_PROVIDER_ID
SERVICE_TITAN_CLIENT_ID
SERVICE_TITAN_CLIENT_SECRET
Connecting the Frontend with the Backend
Now that we've built both the frontend form and the backend API, it's time to connect them. We'll update our form to submit data to our backend action and enhance the user experience with responsive feedback.
Step 1: Integrate the Server Action into the Form
We'll modify our BookingForm
component to handle form submission using server actions, ensuring secure processing of form data.
Update BookingForm.tsx
Open src/components/BookingForm.tsx
and make the following changes:
Explanation:
- Line 2: Ensure we have
use client
enabled for client-side rendering since our form leverages client-side state management likeuseState
. - Lines 16-21: Initialize state for
serverActionResult
and create aformRef
usinguseRef
to reset the form after submission. - Lines 23-35: Define the
handleCreateBooking
function, which calls thecreateBooking
action, updates the state with the result, shows toast notifications, and resets the form on success. - Line 39: Update the JSX to include the
<Toaster />
component for toast notifications - Line 41-42: Attach the
formRef
to the<form>
element and set theaction
prop tohandleCreateBooking
- Line 51-60: Conditionally display success or error messages.
Step 2: Making the Submit Button Stateful
We'll enhance the SubmitButton
component to reflect the form submission status, providing better feedback to the user.
Update SubmitButton.tsx
Open src/components/SubmitButton.tsx
and modify it as follows:
Explanation:
- Line 2: Ensure we have
use client
enabled for client-side rendering since our form leverages client-side state management likeuseState
. - Line 7: Destructure
pending
fromuseFormStatus()
to track the form submission state. - Line 12: Disable the submit button when the form is submitting by setting
disabled={pending}
. - Line 15: Change the button text to "Submitting..." when the form is in the pending state.
Step 3: Adding Toast Notifications for User Feedback
We'll use react-hot-toast
to display toast notifications for success and error messages, enhancing the user experience.
Install react-hot-toast
First, install the react-hot-toast
package:
Update package.json
Your package.json
should now include react-hot-toast
in the dependencies:
Explanation:
- Installation: This command adds
react-hot-toast
to your project, allowing you to use toast notifications.
Update BookingForm.tsx
(Continued)
We have already integrated react-hot-toast
in BookingForm.tsx
during Step 1 by importing toast
and Toaster
, and invoking toast.success
and toast.error
within the handleCreateBooking
function.
Note: Ensure that you have added the <Toaster />
component inside the return statement to render the toast notifications.
Step 4: Finalizing the Integration
With these changes, your form now securely submits data to the backend, provides responsive feedback to users, and enhances the overall user experience.
Testing the Integration
With both the frontend and backend set up and connected, it's time to test the entire booking process. In this section, we'll run the application, submit a test booking, verify it in ServiceTitan, and address common issues that might arise.
Step 1: Running the Application
First, let's start the development server to ensure everything is functioning as expected.
Start the Development Server
Open your terminal, navigate to your project directory, and run the following command:
Explanation:
- This command starts the Next.js development server, making your application accessible at
http://localhost:3000
.
Access the Application
Open your preferred web browser and navigate to: http://localhost:3000
You should see the booking form we created earlier.
Step 2: Submitting a Test Booking
Now, let's simulate a user booking by filling out the form.
Fill Out the Form
Enter the following test data into the form fields:
- First Name:
Jane
- Last Name:
Smith
- Email:
jane.smith@example.com
- Phone Number:
(555) 123-4567
- Street Address:
456 Elm Street
- City:
Springfield
- State:
IL
- ZIP Code:
62704
Form Filled Out With Test Data:
Use Test Data
Ensure you're using test data to prevent any unintended real bookings.
Submit the Form
Click the Create Booking button at the bottom of the form.
Observe the Response
- Success Message: If the booking was created successfully, a message like "Booking created successfully." will appear.
- Error Message: If there was an issue, an error message will display with details.
- The form status message will appear below the form, styled in green for success or red for errors.
Successful Form Submission:
Failed Form Submission:
Step 3: Verifying the Booking in ServiceTitan
To confirm that the booking was successfully created, we'll check your ServiceTitan account.
Log into ServiceTitan
- Navigate to ServiceTitan Login and sign in with your credentials.
Locate the New Booking
- Go to the Bookings or Appointments section in your ServiceTitan dashboard.
- Search for the booking under the name "Jane Smith."
Verify Booking Details
- Ensure that all the information matches the data you entered in the form.
- Confirm that the booking status and other details are correct.
Note: It might take a few moments for the booking to appear in ServiceTitan due to processing times.
Step 4: Troubleshooting Common Issues
If you encounter any problems during testing, consider the following troubleshooting tips.
Common Issues and Solutions
- Issue: No success message after form submission.
- Solution: Check the browser console for errors. Ensure that the backend server is running and accessible.
- Issue: Booking doesn't appear in ServiceTitan.
- Solution: Wait a few minutes and refresh the page. Verify that your API credentials are correct and that you have the necessary permissions.
- Issue: Error messages about authentication or authorization.
- Solution: Double-check your environment variables in
.env.local
and ensure all required variables are set correctly.
- Solution: Double-check your environment variables in
Keep in Mind
Ensure that your ServiceTitan API credentials are valid and that your account has permission to create bookings via the API.
Next Steps
Congratulations! You've successfully tested the integration between your Next.js application and ServiceTitan's API. This foundational setup can be expanded to include additional features like scheduling options, service selections, and customer authentication.
By integrating with ServiceTitan, you're streamlining your booking process and enhancing the customer experience. This kind of seamless integration is crucial for modern businesses looking to stay competitive and meet customer expectations.
Conclusion: Empowering Your Service Business with Modern Integration
Throughout this tutorial, we've journeyed through the process of integrating a Next.js application with ServiceTitan's API to create a seamless booking experience. Let's recap the key milestones we've achieved:
- Project Setup: Cloned the starter repository and set up the development environment.
- Building the Booking Form UI: Created a responsive booking form using React components and Tailwind CSS.
- Creating the Backend API:
- Developed server-side actions to securely process form submissions.
- Configured authentication with ServiceTitan's API.
- Connecting Frontend and Backend:
- Integrated the frontend form with the backend action.
- Enhanced user experience with real-time feedback using
react-hot-toast
.
- Testing the Integration:
- Successfully submitted test bookings and verified them in ServiceTitan.
- Addressed common issues to ensure a robust implementation.
By following these steps, you've built a functional booking system that not only streamlines your operations but also enhances customer engagement. This integration serves as a solid foundation for further enhancements and scaling your service business.
Next Steps
With the groundwork laid, consider expanding your application with additional features:
- Automate Customer Support Workflows: Upon bookings, send automated confirmations, reminders, and advance payment collection requests to customers.
- Scheduling Options: Allow customers to select preferred service dates and times.
- Service Selection: Enable customers to choose from a list of services you offer.
- User Authentication: Implement account creation and login functionality for returning customers.
- Data Analytics: Integrate tools to analyze booking trends and customer behavior.
By continuing to innovate and adapt, you'll stay ahead in a competitive market, offering unparalleled service and convenience to your customers.
Partner with Aclarify for Success
While you've made significant progress, taking your service business to the next level often requires expert guidance and resources. That's where Aclarify comes in.
Why Choose Aclarify?
- Deep Expertise: Our team specializes in integrating ServiceTitan with cutting-edge web technologies, ensuring seamless and efficient solutions.
- Customized Solutions: We tailor our services to meet your specific business needs, providing a bespoke approach rather than off-the-shelf products.
- Dedicated Support: From initial consultation to ongoing maintenance, we're committed to your success every step of the way.
Let's Transform Your Business Together
Imagine a fully integrated system where bookings, customer interactions, and service management are all streamlined and automated. Envision empowering your team with tools that boost productivity and delighting your customers with exceptional service experiences.
At Aclarify, we're passionate about making this a reality for you.
Partner with Aclarify for ServiceTitan Integration Solutions
Our team at Aclarify specializes in custom ServiceTitan integrations that streamline operations, automate scheduling, and enhance customer data management. We ensure ServiceTitan integrates seamlessly with your existing tools, creating a solution tailored precisely to support your business growth.