Build an AI Newsletter Generator SaaS | NextJS, Supabase, OpenAI, TailwindCSS...

By PedroTech

TechnologyAIStartup
Share:

Key Concepts

  • SAS (Software as a Service): A software delivery model where software is licensed on a subscription basis and centrally hosted.
  • LLMs (Large Language Models): AI models trained on vast amounts of text data, capable of generating human-like text.
  • AI Agents: AI systems that can perceive their environment, make decisions, and take actions to achieve specific goals.
  • Authentication: The process of verifying the identity of a user or device.
  • Backend as a Service (BaaS): A cloud service model that provides pre-built backend functionalities, such as authentication, database management, and push notifications.
  • PostgreSQL: An open-source relational database management system (RDBMS).
  • SSR (Server-Side Rendering): Rendering web pages on the server and sending fully rendered HTML to the client.
  • Environment Variables: Variables that store configuration settings and sensitive information, such as API keys, outside of the codebase.
  • Middleware: Software that acts as a bridge between different applications or services, often used to handle authentication, authorization, and request routing.
  • Context API: A React feature that allows sharing data across components without explicitly passing props through each level of the component tree.
  • Event-Driven Function Framework: A framework where functions are executed in response to specific events.
  • Cron-Based Scheduling: Scheduling tasks to run at fixed intervals or specific times using cron expressions.
  • API (Application Programming Interface): A set of rules and specifications that allow different software systems to communicate with each other.
  • News API: An API that provides access to news articles from various sources.
  • OpenAI: An AI research and deployment company that provides access to powerful AI models.
  • Injest: An event-driven function framework designed for building, testing, and operating background operations.
  • Email.js: A service that allows sending emails from client-side JavaScript applications.
  • Markdown: A lightweight markup language used to format text.

1. Introduction and Project Overview

  • The video introduces a course on building a SAS-like web application with AI integration.
  • The project involves creating a service that sends personalized AI-generated newsletters via email.
  • The course utilizes Next.js, OpenAI, Ingest, and Supabase.
  • The complete code is available via a link in the description.

2. Setting Up Next.js and Supabase

  • Creating a Next.js App:
    • The video starts with creating a new Next.js project using the command npx create-next-app.
    • TypeScript, ESLint, Tailwind CSS, and the app router are selected during the setup.
  • Authentication with Supabase:
    • The course uses Supabase for authentication and data storage.
    • Users are instructed to create a Supabase account and a new project.
    • A PostgreSQL database is used with Supabase.
    • Superbase abstracts much of the SQL complexity.
  • Installing Supabase SSR:
    • The @supabase/supabase-js and @supabase/ssr libraries are installed using npm install @supabase/ssr.
  • Creating Utility Files:
    • Four files are created in a lib folder: client.ts, server.ts, middleware.ts, and models.ts.
    • client.ts and server.ts contain code from the Supabase SSR documentation to create Supabase instances for client and server components, respectively.
    • middleware.ts sets up middleware with Supabase access.
    • models.ts is reserved for data models (used later).
  • Environment Variables:
    • A .env.local file is created to store NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY.
    • These values are obtained from the Supabase project dashboard.
  • Middleware Configuration:
    • The middleware.ts file is configured to redirect users from the homepage to the dashboard.
    • Middleware is used to gate access to the sign-in and dashboard pages based on authentication status.

3. Building the Sign-In Page

  • Creating the Sign-In Route:
    • A signin folder is created in the app directory, containing a page.tsx file.
    • The sign-in page includes a form for email and password input.
  • State Management:
    • useState hook is used to manage the email, password, and sign-up status.
  • Form Handling:
    • An handleOff function is created to handle form submission.
    • The function uses superbase.auth.signUp and superbase.auth.signInWithPassword to create and sign in users.
    • Error handling is implemented using a try-catch block.
  • Redirection:
    • The useRouter hook is used to redirect users to the dashboard after successful sign-in.
  • Middleware Integration:
    • Middleware is configured to prevent logged-in users from accessing the sign-in page.

4. Implementing Authentication Logic

  • Authentication Pillars:
    • The video outlines five key pillars of authentication:
      1. Signing in and creating an account.
      2. Tracking user data.
      3. Providing a sign-out option.
      4. Gating pages based on sign-in status.
      5. Handling user log out.
  • Off Context:
    • An OContext is created to share authentication data across the application.
    • The context provides access to the user, session, loading state, and sign-out function.
  • Use Effect Hook:
    • A useEffect hook is used to fetch the user session and update the context state.
  • On Auth State Change:
    • The superbase.auth.onAuthStateChange function is used to listen for authentication events and update the context state accordingly.
  • Nav Bar Component:
    • A NavBar component is created to display the user's email and provide a sign-out button.
    • The useOff hook is used to access the authentication data from the context.

5. Setting Up Ingest for Background Operations

  • Introduction to Ingest:
    • Ingest is introduced as an event-driven function framework for building background operations.
    • It is used to handle the core workflow of the AI newsletter service: fetching news, generating summaries, and sending emails.
  • Ingest Account and Signing Key:
    • Users are instructed to create an Ingest account and obtain a signing key.
    • The signing key is stored in the .env.local file.
  • Installing Ingest CLI:
    • The Ingest CLI is installed using npm install ingest.
  • Starting the Ingest Dev Server:
    • The Ingest dev server is started using npx ingest cli@latest dev.
    • The dev server provides a local environment for testing Ingest functions.
  • Creating Ingest Client:
    • An Ingest client is created in lib/ingest/client.ts using new Ingest({ id: 'ai-newsletter-app' }).
  • Registering Ingest Functions:
    • A functions.ts file is created to register all Ingest functions.
  • Serving HTTP Endpoints:
    • An API route is created in api/ingest/route.ts to serve HTTP endpoints for Ingest.
    • The serve function from @ingest/next is used to handle incoming requests.

6. Building the Scheduled Newsletter Function

  • Creating the Ingest Function:
    • A scheduled-newsletter.ts file is created to define the Ingest function for generating and sending newsletters.
    • The ingest.createFunction method is used to create the function.
    • The function is triggered by the newsletter.schedule event.
  • Fetching News Articles:
    • A fetchNews step is defined to fetch news articles from the News API based on user-selected categories.
    • The News API key is stored in the .env.local file.
    • The fetchArticles function is created in lib/news.ts to handle the API request.
  • Generating AI Summary:
    • A summarizeNews step is defined to generate an AI summary of the fetched articles using OpenAI.
    • The step.ai.infer method is used to call the OpenAI model.
    • The OpenAI API key is stored in the .env.local file.
    • The system and user roles are used to provide instructions to the AI model.
  • Sending Email:
    • A sendEmail step is defined to send the AI-generated newsletter via email using Email.js.
    • The Email.js service ID, template ID, and public key are stored in the .env.local file.
    • The sendEmail function is created in lib/email.ts to handle the Email.js API request.
  • Testing the Ingest Function:
    • The Ingest dev server is used to test the function and inspect the results of each step.

7. Building the User Interface for Category Selection and Delivery Frequency

  • Creating the Select Page:
    • A select folder is created in the app directory, containing a page.tsx file.
    • The select page includes a form for selecting categories and delivery frequency.
  • Category Selection:
    • An array of categories is defined, each with an ID, name, and description.
    • The categories are displayed as checkboxes.
    • The useState hook is used to manage the selected categories.
  • Delivery Frequency Selection:
    • An array of frequency options is defined, each with an ID, name, and description.
    • The frequency options are displayed as radio buttons.
    • The useState hook is used to manage the selected frequency.
  • Saving Preferences:
    • An handleSavePreferences function is created to handle form submission.
    • The function makes a POST request to the api/user-preferences route to save the user's preferences.
  • Creating the User Preferences Route:
    • A user-preferences folder is created in the api directory, containing a route.ts file.
    • The route handles POST requests to save user preferences and GET requests to retrieve user preferences.
    • The superbase.from('user_preferences').upsert method is used to insert or update the user's preferences in the database.

8. Scheduling Newsletters and Managing User Preferences

  • Event-Driven Scheduling:
    • The video explains the concept of event-driven scheduling and how it can be used to schedule the next newsletter delivery.
  • Scheduling the Next Run:
    • A scheduleNext step is added to the Ingest function to schedule the next run of the function.
    • The nextScheduleTime variable is calculated based on the user's selected delivery frequency.
    • The ingest.send method is used to schedule the next run of the function with the calculated timestamp.
  • Pausing and Resuming Newsletters:
    • A PATCH request is created in the api/user-preferences route to update the is_active field in the user_preferences table.
    • The handleDeactivateNewsletter and handleActivateNewsletter functions are created to handle the pause and resume actions.
    • The cancelOn property is used to cancel the scheduled newsletter delivery when the user pauses the newsletter.
    • The ingest.send method is used to trigger the newsletter.schedule.deleted event, which cancels the scheduled run.

9. Conclusion

  • The video provides a comprehensive guide to building a SAS-like web application with AI integration using Next.js, Supabase, OpenAI, and Ingest.
  • The course covers authentication, data storage, background operations, and scheduling.
  • The video emphasizes the importance of using Ingest for managing background operations and scheduling tasks.
  • The presenter thanks Ingest for sponsoring the video.

Chat with this Video

AI-Powered

Hi! I can answer questions about this video "Build an AI Newsletter Generator SaaS | NextJS, Supabase, OpenAI, TailwindCSS...". What would you like to know?

Chat is based on the transcript of this video and may not be 100% accurate.

Related Videos

Ready to summarize another video?

Summarize YouTube Video