# Welcome to Startup Starter Kits (SSK)

Thank you for exploring [**Startup Starter Kits**](https://startupstarterkits.com), the ultimate development toolkit to **launch faster** and **scale smarter**. Whether you're using **SSK-Core** or **SSK-Pro**, our tools and resources provide everything you need to build, manage, and scale your web projects.

***

#### 💡 Why Choose **SSK**?

**SSK** is designed to empower developers by utilizing cutting-edge UI frameworks and providing the flexibility to scale with your project. Here's what makes **SSK** stand out:

1. **🎨 Powered by shadcn/ui, daisyUI, and magicUI**\
   SSK integrates **shadcn/ui**, **daisyUI**, and **magicUI** to give you access to modern UI components out of the box. These frameworks ensure a seamless and customizable user interface experience while adhering to best practices for accessibility and design.
2. **📦 Pre-configured for Efficiency**\
   Skip the setup hassle. With pre-configured setups for **project management**, **automated testing environments**, and **integrations**, focus on building, not configuring.
3. **📚 Comprehensive Documentation**\
   Access detailed **tutorials**, **step-by-step guides**, and **advanced use cases** to navigate every stage of your project efficiently.
4. **🔄 Continuous Updates**\
   Both **SSK-Core** and **SSK-Pro** come with **lifetime updates**, so your project stays modern and secure with the latest technologies.

***

#### 🎁 **SSK Packages**

**SSK-Core**

The perfect starting point for developers and small businesses. Includes:

* **🌟 UI Integration**: Leverage **shadcn/ui**, **daisyUI**, and **magicUI** for fast and beautiful UI components.
* **📚 Detailed Documentation**: Step-by-step guides for quick setup.
* **🔒 Compliance Tools**: Privacy policy and metadata setup to ensure compliance.
* **SEO Optimization**: Built-in SEO best practices for increased visibility.

**SSK-Pro**

For advanced users and enterprises. Everything in **SSK-Core**, plus:

* **📊 Analytics Integration**: Seamless integration with analytics tools.
* **🤖 AI Chatbots**: Integrate AI-powered chatbots for better user engagement.
* **⚖️ GDPR & Cookie Consent**: Ensure compliance with international regulations.
* **🚀 Email Signup**: Built-in support for user signups and notifications.
* **🛒 Affiliate Marketing Options**: Choose between **Rewardful** or **Lemon Squeezy** to easily add affiliate marketing, manage payouts, and grow your reach.

***

#### 🌟 **Become an Affiliate Partner**

Help others discover **Startup Starter Kits** and earn rewards by joining our affiliate program. Promote our tools and resources and earn commissions with each referral. Learn more about becoming a partner [here](https://startupstarterkits.com/#partners).

***

#### 📈 **Stay Updated**

* **Follow us on LinkedIn**: [Three Tech Consulting](https://www.linkedin.com/company/three-tech-consulting)
* **Visit our Website**: [Three Tech Consulting](https://threetech.consulting)

Thank you for exploring [**Startup Starter Kits**](https://startupstarterkits.com)! 🚀 Let's build something great together!

***

Documentation: [SSK-Docs](https://docs.startupstarterkits.com)


# Launch Manual

Comprehensive Tooling with Startup Starter Kits (SSK)

Welcome to the **Startup Starter Kits (SSK) Launch Manual**, designed to help you set up all the tools you need to launch successfully and easily, without sacrificing performance or scalability. This manual will walk you through the setup of essential tools, integrations, and components, enabling you to build your product efficiently while maintaining a robust, scalable foundation.

***

## What's Inside the Launch Manual?

* **Quick Setup**: Get your project up and running in minutes with easy-to-follow instructions on cloning repositories and installing dependencies.
* **Automated Workflows**: Learn how to use the `start-now` command, a custom generator that helps you quickly start a new project. It automatically sets up key pages, including a landing page, 404 page, error page, and more, giving you a solid foundation from the beginning.
* **Frontend & Backend Setup**: Integrate UI components, form handling, reCAPTCHA, and more with pre-built, customizable configurations.
* **Deployment Made Simple**: Follow deployment guides for platforms like **Vercel**, ensuring your project is ready for production with minimal effort.
* **SEO & Metadata**: Configure SEO and Open Graph metadata templates for enhanced visibility and optimization of your project.

***

This Launch Manual will help you streamline your development process and scale your project with ease. Jump into the setup process, integrate core functionalities, and deploy to production in just a few steps. Whether you're starting small or building for enterprise-scale, **SSK** has you covered.


# Clone the Repository and Install Dependencies

Chapter 1:

## Step 1 - Clone the Repository

To begin setting up **Startup Starter Kits (SSK)**, you need to clone the repository for either **SSK-Core** or **SSK-Pro**.

{% hint style="info" %}
To get started with SSK, you'll need to have [Node.js](https://nodejs.org/) version 18 or higher installed on your development machine.
{% endhint %}

### Cloning SSK

{% tabs %}
{% tab title="SSK-Core" %}

```bash
git clone https://github.com/Three-Tech-Consulting/SSK-Core.git
cd SSK-Core
npm install
```

{% endtab %}

{% tab title="SSK-Pro" %}

```bash
git clone https://github.com/Three-Tech-Consulting/SSK-Pro.git
cd SSK-Pro
npm install
```

{% endtab %}
{% endtabs %}

Once dependencies are installed, you’re ready to start the next step.


# Generate NextJS Apps or Components Using ssk-plugin

Chapter 2:

## Step 2 - Turbocharge Your Workflow with the ssk-plugin & Nx Generators

Building new features or components has never been this smooth! With the **ssk-plugin** and **Nx generators**, **SSK** makes creating apps, components, and features a breeze. No need to sweat the small stuff—just run:

```bash
npm run start-now
```

…and watch the magic happen! ✨

***

## Nx Generators – Power and Flexibility Combined

**SSK** leverages the best of Nx’s powerful generators to help you create applications, libraries, or update projects in your monorepo with just a few clicks. It’s flexible, efficient, and designed to keep your projects scalable and future-proof.

Dive deeper here: [Nx Generators Documentation](https://nx.dev/getting-started/nx-cli)

With **SSK**, you can say goodbye to tedious setups and hello to fast, seamless development. 🚀


# Start Your Project in Development Mode

Chapter 3:

## Step 3 - Running the Development Server

To run your project in **development mode** with hot-reloading and fewer restrictions, use the following command:

```bash
npm run dev <app-name>
```

For example:

```bash
npm run dev startupstarterkits.com
```

This will start your app on a local development server, allowing you to see changes in real-time.


# Configure Your Environment Variables

Environment Setup for Startup Starter Kits

Environment variables are the lifeblood of **Startup Starter Kits (SSK)**, giving you the power to customize and control your application’s behavior without touching a single line of code. From essential details like your company’s name to toggling dynamic features, let’s get your environment in perfect shape!

***

### **The Basics – Make It Personal**

Your key environment variables handle branding, URLs, and more. Here’s a quick example:

```bash
# Core Info (Make It Yours!)
NEXT_PUBLIC_COMPANY_NAME="Your Company Name"
NEXT_PUBLIC_EMAIL="contact@yourcompany.com"
NEXT_PUBLIC_COMPANY_WEBSITE="https://yourcompany.com"
NEXT_PUBLIC_FULL_URL="https://yourproduct.com"
```

🌟 **Tip**: Update these with your company’s details to make sure every user touchpoint feels on-brand.

***

### **Feature Flags – Control Features with Ease**

All feature flags in **SSK** are prefixed with `FF_` and let you control features on the fly. Want to run a new integration or disable a feature for testing? Just flip a flag!

#### **Example Feature Flags**

```bash
# Feature Toggles (Simple, Powerful)
FF_REWARDFUL=true
FF_LEMON=false
FF_STRIPE=true
```

These flags allow you to enable or disable features instantly, giving you the flexibility to experiment, test, and roll out new functionality without redeploying.

***

### **Setting Up in Vercel**

When you’re ready to deploy, make sure to add these environment variables in **Vercel**. Navigate to your project’s **Settings** tab, find **Environment Variables**, and add your keys and values. This ensures your application runs smoothly across all environments.

***

With your environment variables and feature flags configured, you’re ready to adapt, scale, and deliver an exceptional user experience! 🚀


# Run Your Project in Production Mode Locally

Chapter 5:

## Step 5 - Running in Production Mode

Running your project in production mode is essential to simulate the behavior of your application in a real-world environment. This allows you to experience how it performs when fully optimized for speed, resource efficiency, and user experience, providing a more accurate understanding of what your live users will experience.

To run your app in production mode locally, use the following command:

```bash
npm run start <app-name>
```

For example:

```bash
npm run start startupstarterkits.com
```

This command triggers a build using @nx/next:build with production-level optimizations enabled, such as:

• **Minification of JavaScript and CSS** for faster loading times.

• **Tree-shaking** to eliminate unused code, reducing bundle size.

• **Code splitting** to load parts of the app on-demand rather than all at once.

• **Static optimization** for pages that can be pre-rendered, speeding up load times.

By running the project locally in production mode, you can catch any performance bottlenecks, configuration issues, or build-related errors before deployment. This ensures that your application is optimized for real-world use, minimizing potential issues in the production environment.

Running in production mode locally is a critical step in your development workflow to ensure that your application runs smoothly, performs efficiently, and is ready for deployment to live users.


# Launch Your Project

Vercel Configuration

You’ve crafted your landing page and fine-tuned your application—now it’s time to launch and make your mark with **Vercel**! Vercel offers blazing-fast deployments and an intuitive platform, making it the perfect partner to showcase your **SSK** projects to the world.

### Ready, Set, Deploy!

After building your application, just a few simple steps stand between you and your live SaaS product:

1. Head to your Vercel dashboard and configure **Build & Output Settings**. Use this build command to prepare for deployment:

   ```bash
   npm run deploy startupstarterkits.com
   ```
2. Ensure Vercel can locate your production build by specifying the **Output Directory**:

   ```bash
   dist/apps/startupstarterkits.com/.next
   ```

### 🎉 Launch Time!

With these settings in place, your application will be built, deployed, and ready to conquer the world. Congratulations—you’re officially live! Now, it’s time to watch your SaaS dream grow and start generating revenue. 🚀

### 📊 Pro-Tip: Monitor Your Success!

Keep an eye on your project’s performance using the Vercel dashboard, where you can track builds, optimize deployments, and ensure your app is lightning-fast. And if you’re rocking **SSK-Pro** with **Google Analytics** integration, you can gain valuable insights into user behavior, engagement, and more.

Happy launching and here's to a successful SaaS journey! 🥂


# UI Components

The **SSK-Core Kit** provides a variety of pre-built UI components that help you accelerate development, integrate seamlessly with popular UI libraries like **shadcn/ui**, **daisyUI**, and **magicUI**, and let you focus on building features instead of configuring repetitive UI elements.

## **Overview**

The **SSK-Core UI Components** are not a full UI library. Instead, they offer essential components that integrate with popular UI frameworks, giving you flexibility and customization options.

### **Libraries Used:**

* **shadcn/ui**: A modern, accessible component library that simplifies complex UI development.
* **daisyUI**: A Tailwind CSS plugin offering easy-to-use, themeable components.
* **magicUI**: Interactive, dynamic components for adding extra engagement and responsiveness to your app.

***

## **Key Features**

### **shadcn/ui**

Integrates with **Tailwind CSS** to provide customizable, accessible components like forms, buttons, and modals—perfect for building dynamic, responsive user interfaces.

### **daisyUI**

Easy-to-use, themeable components that support both light and dark modes natively. Switch between themes with minimal effort.

### **magicUI**

Dynamic UI elements like animations, modals, and more, perfect for creating fluid, interactive user experiences.

***

## **Using UI Components**

The **SSK-Core** UI components are simple to integrate and can be customized with **Tailwind CSS** utility classes. **twMerge** ensures smooth class merging, so you can easily extend or modify components as needed.

***

## **Why Use SSK-Core UI Components?**

1. **🔧 Simplified Development**: Pre-built components that speed up the development process.
2. **🎨 Flexible Design**: Combine **shadcn/ui**, **daisyUI**, and **magicUI** to build custom UI elements tailored to your needs.
3. **🌗 Easy Theming**: Built-in support for light and dark themes, ensuring a consistent user experience across different environments.
4. **📈 Performance Optimized**: Designed for high performance, even with complex UI setups.

***

## **Best Practices**

* Use **SSK-Core** components to maintain consistency in theme and layout across your app.
* Customize UI components with **Tailwind CSS** and **twMerge** for maximum flexibility.
* Leverage built-in support for light and dark themes to ensure a seamless user experience.

***

## **Conclusion**

The **SSK-Core UI Components** offer a powerful, flexible, and efficient way to build responsive, accessible, and customizable user interfaces. By integrating popular libraries such as **shadcn/ui**, **daisyUI**, **magicUI**, and **Google Fonts**, you can quickly create dynamic UIs for any project.


# Root Layout

RootLayout Component for SSK

The **RootLayout** component in **SSK-Core** is crucial for managing your app's overall structure, including themes, fonts, and layout consistency. It ensures a seamless and flexible user experience by integrating with libraries like **shadcn/ui**, **daisyUI**, and **magicUI**.

***

## **Overview**

The **RootLayout** component provides a consistent foundation for your application’s UI. It handles global settings like themes, fonts, and layout structure, simplifying your app's configuration. This component is highly customizable to meet the specific needs of your project.

***

## **Google Fonts Integration**

**SSK-Core** makes it easy to include Google Fonts within your layout. By passing font imports as props to the `RootLayout` component, you can ensure consistent typography across your app.

***

## **Using the RootLayout Component**

### **Core Layout: RootLayout**

The `RootLayout` component serves as the foundation for your app's structure. It manages global settings such as theme and fonts while maintaining consistency across your pages. Apologies for the confusion. Here is the corrected version without any reference to **daisyUI**:

***

### **Theming and Customization**

* **Light and Dark Themes**: Easily toggle between light and dark modes. This functionality is powered by **next-themes**.
* **Utility Classes with Tailwind CSS**: Use **Tailwind CSS** utility classes to extend and modify the UI components as needed.

For further details on how themes work and how to configure them, visit the [theme documentation](https://github.com/TheodorTomas/TTC/blob/main/libs/shared/core/README/libs/shared/core/features/theme/README.md).

***

## **Pro Layout for Advanced Features**

For **SSK-Pro** users, the Pro `RootLayout` offers additional functionality, including advanced features that are ideal for enterprise-level applications:

* **Analytics Integration**: Built-in support for Google Analytics and other analytics providers.
* **Cookie Consent and GDPR Compliance**: Includes cookie consent management to meet GDPR requirements.
* **Affiliate Marketing Support**: Easily enable affiliate marketing integrations like **Rewardful** or **Lemon Squeezy** with feature flags.
* **reCAPTCHA Support**: Direct integration with **Google reCAPTCHA** to secure forms.

To use the **Pro RootLayout**, import it from `@pro/RootLayout.tsx` and configure the necessary **fonts** and **feature flags**.

***

## **Why Use RootLayout?**

1. **🔧 Simplified App Structure**: Streamline layout configuration with global settings for themes and fonts.
2. **🎨 Easy Theming**: Switch between light and dark modes with minimal setup.
3. **📈 Performance Optimized**: Designed to ensure high performance even with complex layouts.
4. **⚡ Flexible Integration**: Seamlessly integrates with other SSK-Core components and libraries like **Tailwind CSS**.

***

## **Best Practices**

* Use **RootLayout** to ensure consistency across your app.
* Leverage the **Pro RootLayout** for advanced features and integrations in **SSK-Pro**.
* Pass fonts as props to maintain consistent typography across all pages.

***

## **Conclusion**

The **RootLayout** component in **SSK-Core** provides a solid foundation for your app, offering theme management, font integration, and layout structure. It is customizable and adaptable, allowing you to focus on building your app’s core features while ensuring a cohesive user interface.

For **SSK-Pro** users, the **Pro RootLayout** offers additional features and integrations for larger, more complex projects.


# SEO

SEO and Open Graph Configuration for SSK

The **SSK Generator** comes equipped with a handy feature to automatically generate a siteMetadata template for easy management of SEO and Open Graph data. This simplifies setting up your site's metadata, ensuring proper integration with search engines and social platforms.

***

## **Site Metadata Template**

When using the **SSK Generator**, a pre-configured siteMetadata file is generated in:

```bash
apps/startupstarterkits.com/app/_constants/site-metadata.ts
```

This file includes instructions on how to configure SEO fields such as the title, description, and Open Graph images. The generated template ensures that you can easily modify your SEO and Open Graph settings for your site.

***

### **Pre-built Pages with SEO Configs**

All pre-built pages, like the **Privacy Policy** and **Terms of Service**, already include their own siteMetadata configurations. You can reuse the metadata for these pages easily by importing them as follows:

```typescript
export const metadata: Metadata = PrivacyPolicy.metadata
```

This method helps maintain consistent SEO configurations across your pre-built and custom pages.

### How to Use Site Metadata

Once the siteMetadata file is generated, it can be imported and used in your layout files. Here’s an example of how you can configure the metadata in your layout component:

```typescript
import siteMetadata from '_constants/site-metadata'

export const metadata = siteMetadata
```

This setup ensures that your entire website is configured with the appropriate SEO, Open Graph data, and structured metadata right from the layout level.

### Additional Instructions

• **Custom Pages**: For custom pages, you can extend or modify the generated siteMetadata file by changing the title, description, or adding more SEO elements (such as robots or canonical URLs).

• **SEO Best Practices**: Ensure that the title and description are concise and targeted, and that Open Graph images are properly defined for social media sharing.

By using the SSK Generator, configuring SEO and Open Graph metadata becomes straightforward, ensuring your site is optimized and ready for search engines and social media platforms.

***

## **Using JSON-LD for Rich Results**

To further enhance your site's SEO, the SSK Generator also supports **JSON-LD Schema** for generating **Rich Result Text**. This allows your site to integrate structured data that helps Google and other search engines display rich snippets in search results, improving visibility and click-through rates.

The JSON-LD schema is located in:

```bash
libs/shared/core/ui/JsonLdSchema.tsx
```

You can easily integrate JSON-LD by importing and using the schema in your pages or components, like this:

```typescript
import JsonLdSchema from 'libs/shared/core/ui/JsonLdSchema'

const pageMetadata = {
  '@context': 'https://schema.org',
  '@type': 'WebPage',
  name: 'Page Title',
  description: 'Description of the page content',
}

<JsonLdSchema data={pageMetadata} />
```

This integration helps your content stand out on search engine results pages (SERPs) and enhances the visibility of your site across various platforms.


# Icons

## Introduction

In today’s web environment, having properly configured favicons is essential for your app’s appearance across various devices and browsers. This guide explains how to set up favicons in your Next.js app using the Startup Starter Kits (SSK).

## Why Use a Minimal Set of Icons?

Traditionally, setting up favicons required generating over 20 icon files for different devices. We streamline this by reducing it to just five icons and one JSON file, simplifying the process while maintaining consistency.

### SSK-Core Configuration

SSK-Core provides predefined files and tools to help you set up favicons and other site metadata. With this setup, integrating the necessary icons for modern browsers and devices is simple.

### Icon Specifications

1. **Favicon.ico**: One ICO file for legacy browsers at sizes **16x16** and **32x32**.
2. **SVG Icon**: Scalable SVG for modern browsers, ensuring high quality across resolutions.
3. **Apple Touch Icon**: **180x180 PNG** icon with a **20px border** for home screen shortcuts.
4. **Web App Manifest**: Optional for Progressive Web Apps (PWAs). If needed, include **192x192 PNG**, **512x512 maskable icon**, and **512x512 splash screen icon** for web app installation.

### Additional Resources

For a more in-depth exploration of favicon management, check out [Favicons Made Simple](https://theodortomas.com/articles/favicons-made-simple).

## Conclusion

With this setup, your web app will look great across all platforms. SSK-Core simplifies favicon management, making a traditionally complicated task easy. If you have questions, feel free to reach out!


# Feature Flags

This utility provides a flexible and powerful way to manage feature toggling in your **SSK-Pro** project. By leveraging environment-driven feature flags, you can enable or disable features without modifying the codebase, making it easy to adapt to different environments, perform A/B testing, or selectively roll out features.

## **Why This Approach is Valuable**

* **Dynamic Control**: Features can be turned on or off based on environment variables, allowing for rapid adjustments without code changes.
* **Seamless Integration**: Works with both server and client components, ensuring consistent feature management across your application.
* **Automatic Detection**: All environment variables prefixed with `FF_` are automatically detected as feature flags.
* **Scalability**: Easily extend or modify feature rules based on roles, percentages, or other criteria using simple configuration.

## **Setup**

The utility automatically checks for environment variables prefixed with `FF_` and makes them available as feature flags throughout your application. Simply add or modify these variables in your `.env` file to control features.

### **Environment Variable Configuration**

To add a new feature flag, simply add an environment variable with the `FF_` prefix:

```properties
# .env file
FF_MY_FEATURE="true"  # Enable a feature
FF_ANOTHER_FEATURE="false"  # Disable a feature
```

The feature flags are automatically detected and available in both server and client components without any additional setup.

### **Server-Side Feature Flag Checks**

For server-side logic, use `checkIsFeatureFlagEnabled()` to read environment variables directly:

```typescript
import { checkIsFeatureFlagEnabled } from '@core/feature-flags/utils'

function someServerFunction() {
  if (checkIsFeatureFlagEnabled('MY_FEATURE')) {
    // Perform server-side logic for enabled feature
    console.log('My Feature is enabled')
  }
}
```

### **Client-Side Feature Flag Checks**

For client-side components, use the `useCheckIsFeatureEnabled` hook to access the feature flags from the context.

```tsx
import React from 'react'
import { useCheckIsFeatureEnabled } from '@core/feature-flags/FeatureFlagProvider'

function MyComponent() {
  const checkIsFeatureEnabled = useCheckIsFeatureEnabled()

  const isFeatureOneEnabled = checkIsFeatureEnabled('FEATURE_ONE')

  if (!isFeatureEnabled) {
    return null
  }

  return (
    <div>
      <p>Feature One is enabled!</p>
    </div>
  )
}
```

### **Conditional Rendering with `FeatureEnabled` Component**

The `FeatureEnabled` component can be used to conditionally render UI elements based on feature flags.

```tsx
import FeatureEnabled from '@core/feature-flags/FeatureEnabled'

function ExampleComponent() {
  return (
    <div>
      <FeatureEnabled featureFlag="FEATURE_ONE">
        <p>This content is shown if FEATURE_ONE is enabled.</p>
      </FeatureEnabled>
      <FeatureEnabled featureFlag={['FEATURE_ONE', 'FEATURE_TWO']}>
        <p>
          This content is shown if either FEATURE_ONE or FEATURE_TWO are
          enabled.
        </p>
      </FeatureEnabled>
    </div>
  )
}
```

***

## **Core Functions**

### `checkIsFeatureFlagEnabled(featureName: string)`

* **Description**: Checks if a feature flag is enabled by reading from environment variables (used in server-side code).
* **Returns**: `true` if the feature is enabled, otherwise `false`.

### `useCheckIsFeatureEnabled()`

* **Description**: A React hook for checking if a feature flag is enabled (used in client-side components).
* **Returns**: A function to check if a feature is enabled.

### `FeatureEnabled` Component

* **Props**:
  * `featureFlag` (`string | string[]`): The feature flag(s) to check.
  * `children` (`React.ReactNode`): The elements to render if the feature flag is enabled.
* **Description**: Conditionally renders its children based on the specified feature flags.

***

## **Final Notes**

This feature flagging approach ensures that only explicitly defined features are togglable, minimizing unintended behaviors across environments. It seamlessly integrates into server and client components, providing robust and dynamic control over your application's features.

For a detailed breakdown of feature flags, including advanced use cases like A/B testing, percentage-based rollouts, and user role-based features, visit [**Feature Flags at Zero Cost**](https://theodortomas.com/articles/feature-flags-at-zero-cost).

**Happy toggling!**


# Utilities

The **SSK-Core** utilities module provides essential helper functions designed to streamline environment management, client/server detection, and secure access to environment variables. These utilities are a core part of **SSK-Core**'s functionality, simplifying tasks that are commonly needed across different areas of your project.

***

### **Core Features**

1. **Environment Detection**: Easily determine if the code is running in a development environment or whether it’s executing on the client (browser) or server (Node.js).
2. **Dynamic Host Retrieval**: Automatically retrieve the host URLs depending on whether you’re working locally or in a production environment, making it simple to manage local and production setups.
3. **Environment Variable Access**: Securely fetch and validate environment variables with flexible error handling. This reduces the chance of runtime failures by ensuring that essential variables are always available in production environments.

***

### **How to Use**

#### **1. Client-Side Environment Variable Validation**

Use `checkRequiredEnvVar` to ensure critical environment variables are defined on the client side. It allows for flexible handling during development and strict enforcement in production.

**Example**:

```typescript
import { checkRequiredEnvVar } from '@core/utils'

const apiUrl = checkRequiredEnvVar(
  'NEXT_PUBLIC_API_URL',
  process.env.NEXT_PUBLIC_API_URL,
)
console.log(`API URL: ${apiUrl}`)
```

* **Development Behavior**: Logs an error if the variable is missing but allows you to continue.
* **Production Behavior**: Throws an error if the variable is missing, preventing potentially unstable behavior.

***

#### **2. Server-Side Environment Variable Retrieval**

Use `getEnvVar` to safely fetch and validate environment variables in server-side code. This utility ensures secure access and avoids unintended exposure of environment variables to the client.

**Example**:

```typescript
import { getEnvVar } from '@core/utils'

const dbConnectionString = getEnvVar('DATABASE_URL')
console.log(`Database Connection String: ${dbConnectionString}`)
```

* **Server-Side Only**: Throws an error if used on the client side.
* **Integrated Validation**: Automatically leverages `checkRequiredEnvVar` for robust validation.

***

### **Other Utilities**

#### **Development Environment Check**

Verify if the project is running in a development environment:

```typescript
if (checkIsDev()) {
  console.log('Development mode is active')
}
```

#### **Host URL Retrieval**

Retrieve the appropriate host URL based on the environment using `getHost`:

```typescript
const currentHost = getHost()
console.log(`Current host: ${currentHost}`)
```

This feature ensures that both local development and production environments are handled seamlessly, reducing issues with hardcoded URLs.

***

By leveraging these utilities, you can streamline environment management, improve development efficiency, and ensure a smooth transition between local and production environments.


# Templates

SSK-Core provides customizable templates to help you quickly set up essential legal and informational documents. These templates serve as a base that can be tailored to meet your specific needs and are configurable through environment variables.

### Available Templates

1. [Privacy Policy Template](/ssk-core-features/index/privacy-policy): A customizable privacy policy template to communicate your commitment to user data protection and transparency.
2. [Terms of Service Template](/ssk-core-features/index/tos): A terms of service template that outlines the rules and guidelines for users of your application.

Each template can be configured with environment variables, allowing you to modify certain details (such as company name, contact information, and policies) without altering the template files directly.

***

Use these templates as a foundation and adjust them to align with your project requirements.


# Privacy Policy Template

This guide explains how to set up and use the **Privacy Policy** template in your **SSK** project. The **Privacy Policy** page includes dynamic content such as company name, email, and other environment variables for easy configuration.

## Steps to Use the Template

### 1. Create a Privacy Policy Page

First, create a directory for your **Privacy Policy** page under the `apps/<app-name>` folder:

```bash
apps/<app-name>/privacy-policy/page.tsx
```

Inside this file, copy the PrivacyPolicy component code provided. This template dynamically pulls information from environment variables, such as the company name, product name, and contact email.

#### 2. Set Environment Variables

Make sure to set the required environment variables in your .env file:

```bash
NEXT_PUBLIC_COMPANY_NAME=YourCompanyName
NEXT_PUBLIC_PRODUCT_NAME=YourProductName
NEXT_PUBLIC_EMAIL=contact@yourcompany.com
NEXT_PUBLIC_WEBSITE_CONTACT=https://www.yourcompany.com/contact
NEXT_PUBLIC_COUNTRY=YourCountry
```

These environment variables will be used in the Privacy Policy template for personalization, such as in the company name, contact email, and website.

#### 3. Define Metadata for the Privacy Policy Page

The Privacy Policy template allows you to define custom metadata for the page. This metadata can be used for SEO and Open Graph purposes.

In the page.tsx file, define the metadata object:

```tsx
export const metadata: Metadata = PrivacyPolicy.metadata
```

This ensures the correct usage without unnecessary redefinition of metadata.

#### 4. Customize the Content

The Privacy Policy template includes sections for legal terms like Information We Collect, How We Use Your Information, Sharing Your Information, etc. You can modify or add additional sections as needed to suit your business requirements.

#### 5. Render the Privacy Policy Page

Finally, you can render the Privacy Policy page in your application’s routing configuration. The file located at apps//privacy-policy/page.tsx will automatically be picked up by Next.js as a route.

```tsx
import React from 'react'

import { type Metadata } from 'next'

import Page from '@core/ui/Page'
import PrivacyPolicy from '@core/ui/PrivacyPolicy'

export const metadata: Metadata = PrivacyPolicy.metadata

export default function PrivacyPolicyPage() {
  return (
    <Page>
      <PrivacyPolicy />
    </Page>
  )
}
```

With this guide, you can easily create a professional Privacy Policy page in your project, complete with SEO optimizations and dynamic content.


# Terms of Service Template

This guide explains how to set up and use the Terms of Service (ToS) template in your SSK project. The ToS page includes dynamic content such as company name, email, and other environment variables for easy configuration.

## Steps to Use the Template

### 1. Create a ToS Page

First, create a directory for your Terms of Service page under the `apps/<app-name>` folder:

```bash
apps/<app-name>/tos/page.tsx
```

Inside this file, copy the TermsOfService component code provided. This template dynamically pulls information from environment variables, such as the company name, product name, and contact email.

#### 2. Set Environment Variables

Make sure to set the required environment variables in your .env file:

```bash
NEXT_PUBLIC_COMPANY_NAME=YourCompanyName
NEXT_PUBLIC_PRODUCT_NAME=YourProductName
NEXT_PUBLIC_EMAIL=contact@yourcompany.com
NEXT_PUBLIC_WEBSITE_CONTACT=https://www.yourcompany.com/contact
NEXT_PUBLIC_COUNTRY=YourCountry
```

These environment variables will be used in the Terms of Service template for personalization, such as in the company name, contact email, and website.

#### 3. Define Metadata for the ToS Page

The ToS template allows you to define custom metadata for the page. This metadata can be used for SEO and Open Graph purposes.

In the page.tsx file, define the metadata object:

```tsx
export const metadata: Metadata = TermsOfService.metadata
```

This ensures the correct usage without unnecessary redefinition of metadata.

#### 4. Customize the Content

The Terms of Service template includes sections for legal terms like User Data and Security, Prohibited Conduct, Ownership and Rights, etc. You can modify or add additional sections as needed to suit your business requirements.

#### 5. Render the ToS Page

Finally, you can render the Terms of Service page in your application’s routing configuration. The file located at apps//tos/page.tsx will automatically be picked up by Next.js as a route.

```tsx
import React from 'react'

import { type Metadata } from 'next'

import Page from '@core/ui/Page'
import TermsOfService from '@core/ui/TermsOfService'

export const metadata: Metadata = TermsOfService.metadata

export default function TermsOfServicePage() {
  return (
    <Page>
      <TermsOfService />
    </Page>
  )
}
```

With this guide, you can easily create a professional Terms of Service page in your project, complete with SEO optimizations and dynamic content.


# AI Chat Integration

AI Chat Integration Guide for SSK Pro

Unlock the power of AI-driven conversations in your **Startup Starter Kits (SSK)** project with seamless chatbot integration. This guide will walk you through setting up advanced chat functionality that leverages **OpenAI** and other industry-leading AI providers to create responsive, intelligent chatbot interactions. With built-in security features—such as reCAPTCHA protection, input validation, and rate limiting—you can confidently deploy scalable and secure chat experiences tailored to your users’ needs.

### Why Integrate AI Chat with SSK Pro?

Adding AI chat capabilities to your application can enhance user engagement, automate support, and create dynamic user interactions—all without the need to start from scratch. With SSK Pro, you’re not just adding a chatbot; you’re implementing a robust, scalable, and secure AI solution built to grow with your startup.


# Setting Up AI Providers

Chapter 1:

## Step 1 - Configure Your AI Provider

1. Set up your account with **OpenAI** or another AI provider.
2. Obtain your **API Key** and add it to your `.env` file.

```env
OPENAI_API_KEY=your-openai-api-key
CHAT_BOT_MODEL=gpt-4
```

## Step 2 - Wrapping Your App with the AI Provider

In SSK-Pro, the @pro/RootLayout component handles wrapping your entire app in the AI provider. This ensures that AI services, such as chatbots or dynamic content generation, are available throughout your application without additional manual setup.

Simply configure the environment variables, and the AI provider will be globally accessible through the @pro/RootLayout component.

By following these steps, you will have your AI provider integrated into your application. For more information on additional configurations and AI provider support, visit the SSK-Pro documentation.


# Using the Pre-built Chat Component

Chapter 2:

## Step 2 - Implement the Chat Component

SSK provides a pre-built chat component with AI support. Here’s how to use it:

```tsx
import Chat from './Chat'

// Include the chat component in your page
function Example() {
  return (
    <div>
      <h1>Chat with our AI Assistant</h1>
      <Chat />
    </div>
  )
}
```


# Securing Chatbot Conversations

Chapter 3:

## Step 3 - Implementing Secure Chatbot Conversations

Using chatbots can lead to high API costs if they are not properly secured. To protect against spam and control usage, SSK-Pro provides essential security features, including rate limiting, reCAPTCHA integration, and input validation.

## Importance of Securing API Usage

Allowing unrestricted access to your chatbot API can lead to abuse, excessive usage, and increased costs. Implementing robust security features like rate limiting, reCAPTCHA, and input validation ensures responsible use, controls expenses, and protects your API resources.

## Key Security Features

### 1. **Rate Limiting**

SSK-Pro includes rate limiting powered by [Upstash](https://upstash.com/), which restricts the number of requests a user can make within a specific timeframe. This helps prevent excessive use and spam.

* **Example**: In SSK-Pro, the chatbot API is rate-limited to 5 requests per 10 seconds per IP address. This minimizes potential abuse while ensuring fair access.

### 2. **reCAPTCHA Integration**

To protect against automated bots, SSK-Pro integrates Google reCAPTCHA, which verifies user interactions and prevents bot activity.

* **Implementation**: Each form submission requires a reCAPTCHA token, which is verified server-side. This helps ensure that interactions come from legitimate users.

### 3. **Input Validation**

SSK-Pro validates all incoming user inputs to prevent malicious or unexpected data from reaching the chatbot API. This validation process helps protect against injection attacks and ensures smooth operation by accepting only expected input formats.

## Using `continueConversation` with Security Features

The `continueConversation` function in SSK-Pro integrates all these security features seamlessly, making it easy to handle user interactions securely.

Here’s how you can call `continueConversation` in your component with the reCAPTCHA token:

```tsx
import { continueConversation } from './ai/actions'

// Securely call this function when the user submits a message
const response = await continueConversation(userInput, recaptchaToken)
```

In this configuration, `continueConversation` will:

* Verify the reCAPTCHA token to prevent bot activity
* Enforce rate limiting based on the user's IP address
* Validate user input for safe, predictable interactions

By securing your chatbot API, SSK-Pro helps you reduce potential costs, prevent abuse, and ensure your chatbot service is protected and reliable.


# Testing and Customizing AI Responses

Chapter 4:

## Step 4 - Test Your Chatbot

1. Run your local development server.
2. Test your chatbot by submitting messages and ensuring the AI responds appropriately.
3. Adjust response handling and customize welcome messages in the chatbot’s configuration if necessary.

## Step 5 - Customizing AI Prompts

You can also customize the AI’s responses by editing the prompt used for generating replies:

```tsx
export const PROMPT_PREFIX = `As the SSK-Assistant, answer a potential customer’s question...`
```


# Google Analytics

Integrating Google Analytics with Custom Components

In this guide, I’ll walk you through how to integrate Google Analytics into your Next.js application using the provided custom components. This setup allows you to track user interactions, monitor page views, and handle cookie consent efficiently.


# Setting Up Google Analytics

Chapter 1:

Step 1 - Create a Google Analytics Property

1\. Sign in to your [Google Analytics account](https://analytics.google.com).

2\. In the Admin section, create a new property and follow the steps.

3\. After property creation, navigate to Data Streams and select Web.

4\. Copy your Measurement ID (GA\_MEASUREMENT\_ID). It looks like G-XXXXXXXXXX.

## Step 2 - Add Your Measurement ID to .env

1\. Open your .env.local file (create it if it doesn’t exist).

2\. Add your Google Analytics Measurement ID under the variable name NEXT\_PUBLIC\_GA\_MEASUREMENT\_ID.

```
NEXT_PUBLIC_GA_MEASUREMENT_ID=G-XXXXXXXXXX
```


# Implementing Pageview Tracking

Chapter 2:

## Step 3 - Add Google Analytics to Your Application

For users of the SSK Pro version, the Google Analytics integration is already included in the RootLayout component, which automatically injects the GoogleAnalytics component into your app. This means that tracking page views is handled globally without any additional setup required from your end.

Here’s how the RootLayout in SSK Pro includes Google Analytics:

```
import { GoogleAnalytics } from '@pro/analytics/GoogleAnalytics'

function RootLayout() {
  return (
    <>
      <GoogleAnalytics />
      {/* Other SSK-Pro features */}
    </>
  )
}
```

**What this means:**

* **No manual integration needed**: Since the GoogleAnalytics component is already integrated in the RootLayout, it automatically tracks page views and user behavior site-wide.
* **Page view tracking is automatic**: Every page you add to the Pro version of your app will already be tracked by Google Analytics. Just ensure that the GA\_MEASUREMENT\_ID environment variable is correctly set.
* **Cookie consent handling**: The Google Analytics setup respects the user’s cookie consent, so data is only sent if users have agreed to it.

**In summary**: For Pro users, the Google Analytics tracking functionality is baked into the foundation of your application via the RootLayout. You simply need to ensure that your Google Analytics Measurement ID is correctly added to your .env file.


# Handling Cookie Consent

Chapter 3:

## Step 4 - Integrate Cookie Consent

To ensure GDPR compliance, you’ll need to ask users for cookie consent before tracking. The CookieConsent component handles this.

```
import { CookieConsent } from '@pro/analytics/CookieConsent'

function MyApp() {
  return (
    <>
      <CookieConsent>
        🍪 We use cookies to improve your experience. By using our site, you accept cookies.
      </CookieConsent>
      {/* Rest of your app */}
    </>
  )
}
```

* When a user accepts cookies, it automatically enables tracking.
* The cookie consent value is stored, ensuring that analytics only run after consent is granted.


# Tracking Events

Chapter 4:

## Step 5 - Send Custom Events

You can use the Link component to send custom events to Google Analytics when users interact with links.

```
import { Link } from '@pro/analytics/Link'

<Link
  href="/contact"
  eventData={{
    event: 'click',
    category: 'Navigation',
    action: 'Click Contact',
    label: 'Contact Us',
    value: 1,
  }}
>
  Contact Us
</Link>
```

* When the link is clicked, it sends a custom event (gtag('event', ...)) to Google Analytics.
* You can customize the event details, such as category, action, and label.

**Additional Utility Functions:**

* sendAnalyticsEvent: Manually sends a custom event.
* pageview: Tracks page views.
* acceptCookies: Updates consent to enable analytics.


# Payments Integration

When it comes to getting paid, **SSK-Pro** gives you two awesome choices: **Stripe** for total control and scalability, or **Lemon Squeezy** for simplicity and ease. Whatever your business model, we’ve got you covered.

***

## **Which Payment Solution is Right for You?**

### **💳 Stripe + Rewardful - When You’re Ready to Scale**

If you’re racking up sales, **Stripe** paired with **Rewardful** keeps costs predictable:

* **Flat Monthly Fee**: As your sales volume grows, you’ll save big with predictable costs.
* **Custom Everything**: Design checkout flows and payment experiences exactly the way you want.
* **Global Reach**: Accept payments worldwide, no sweat.

### **🍋 Lemon Squeezy - No Monthly Fees, Just Simple Payments**

**Lemon Squeezy** is all about easy, breezy payment management:

* **Percentage-Based Fees**: No monthly costs. Pay a small percentage on each sale—ideal for startups and lean teams.
* **Fast Setup**: Get started in no time. Manage payments and affiliates all in one spot.
* **Perfect for Startups**: Keep upfront costs low and focus on building your dream.

### **Why We Offer Both**:

* **Flexibility Matters**: Lemon Squeezy is great for keeping costs low when you’re just starting, while **Stripe + Rewardful** shines when you’re scaling big.
* **Avoid Mixing & Matching**: Combining both solutions can increase costs and complexity. Pick the one that works best for your stage of growth.

***

## **Configuring Your Environment Variables**

### **Stripe Configuration**:

```bash
STRIPE_SECRET_KEY="your-stripe-secret-key"
STRIPE_WEBHOOK_SECRET="your-stripe-webhook-secret"
NEXT_PUBLIC_PRIMARY_CTA_STRIPE="" # Optional: Primary call-to-action URL for Stripe
NEXT_PUBLIC_SECONDARY_CTA_STRIPE="" # Optional: Secondary call-to-action URL for Stripe
```

**Webhook Secret**: Secures communication for important payment notifications.

### **Lemon Squeezy Configuration**:

```bash
NEXT_PUBLIC_PRIMARY_CTA_LEMON="#" # Optional: Primary call-to-action URL for Lemon Squeezy
NEXT_PUBLIC_SECONDARY_CTA_LEMON="#" # Optional: Secondary call-to-action URL for Lemon Squeezy
NEXT_PUBLIC_LEMON_STORE="ssk" # Your Lemon Squeezy store identifier
LEMONSQUEEZY_WEBHOOK_SECRET="your-lemon-webhook-secret"
```

**Webhook Secret**: Ensures secure handling of purchase and subscription notifications.

***

## **Get the Most Out of Your Payments Setup**:

* **Keep It Secure**: Protect your API keys at all times.
* **Test Extensively**: Make sure everything works perfectly in sandbox/test mode before you go live.
* **Grow Your Way**: Select the solution that fits your needs and adapt as your business scales.


# Stripe Payments

This guide provides detailed instructions for integrating **Stripe** into your **SSK-Pro** project. With Stripe, you can manage payments securely, and with optional affiliate marketing through **Rewardful**. Stripe is ideal for projects with high transaction volumes and custom affiliate needs.

***

## **Overview**

The Stripe integration in **SSK-Pro** includes:

* **Payment Processing**: Seamlessly handle payments and subscriptions through Stripe.
* **Optional Affiliate Marketing**: Leverage Rewardful for affiliate marketing, ideal for scaling projects with high transaction volumes.
* **GitHub Integration**: Automatically add customers as collaborators to your GitHub repositories after successful purchases.
* **Feature Flag Flexibility**: Use environment-controlled feature flags to toggle Stripe and Rewardful as needed (incompatible with Lemon Squeezy).

***

## **Prerequisites**

Before getting started, ensure the following:

* **Stripe Environment Variables**: Obtain your `STRIPE_SECRET_KEY` and `STRIPE_WEBHOOK_SECRET` for secure payment processing.
* **Rewardful Environment Variable** (optional): `NEXT_PUBLIC_REWARDFUL_API_KEY` if using Rewardful.
* **Environment Feature Flags**:
  * `FF_STRIPE="true"` to enable Stripe (set to `false` if using Lemon Squeezy).
  * `FF_REWARDFUL="true"` to enable Rewardful with Stripe.(optional)

***

## **Getting Started**

Follow these chapters to configure and integrate Stripe into your **SSK-Pro** project:

* [**Chapter 1: Setting Up Your Stripe Account**](/ssk-pro-features/payments/index/chapter-1)\
  Learn how to create a Stripe account, generate API keys, and set up your environment variables for secure payment handling.
* [**Chapter 2: Installing Stripe in Your Application**](/ssk-pro-features/payments/index/chapter-2)\
  Instructions for setting up the Stripe SDK and integrating payments, along with optional Rewardful setup for affiliate marketing.
* [**Chapter 3: Configuring the Webhook Endpoint**](/ssk-pro-features/payments/index/chapter-3)\
  Set up a secure API route to handle incoming Stripe events like `checkout.session.completed` and process customer data.

***

For additional information on Stripe’s webhook specifications, refer to their [official documentation](https://stripe.com/docs/webhooks). This guide ensures that your Stripe integration in **SSK-Pro** is secure, customizable, and configured to work with feature flags, providing flexibility in managing your payment and affiliate solutions.


# Setting Up Your Stripe Account

Chapter 1: Setting Up Your Stripe Account

## **Step 1 - Create a Stripe Account**

1. **Sign Up**: Visit [Stripe](https://stripe.com) and sign up for an account if you don't already have one.
2. **Dashboard Access**: After setting up your account, log in to access the Stripe Dashboard.

## **Step 2 - Obtain API Keys**

1. **Navigate to API Keys**: In the Stripe Dashboard, go to **Developers** > **API keys**.
2. **Copy Keys**:
   * **Publishable Key**: Copy your Publishable Key.
   * **Secret Key**: Copy your Secret Key.
3. **Add to Environment Variables**: In your project's `.env` file, add the following:

   ```bash
   STRIPE_SECRET_KEY=sk_test_your_secret_key
   STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret
   ```

Replace your\_secret\_key, and your\_webhook\_secret with your actual keys.

## **Step 3 - Set Up Webhook Secret**

1. **Navigate to Webhooks**: In the Stripe Dashboard, go to Developers > Webhooks.
2. Add Endpoint:
   * Click on Add endpoint.
   * Enter your webhook endpoint URL (e.g., <https://yourdomain.com/api/webhook>).
3. Select Events:
   * Choose checkout.session.completed and any other events you want to handle.
4. Retrieve Webhook Secret:
   * After creating the endpoint, click to reveal the Signing Secret.
   * Add this to your .env file as STRIPE\_WEBHOOK\_SECRET.


# Installing Stripe in Your Application

Chapter 2: Configuring the Stripe Webhook in Your Application

## **Step 4 - Configure the Webhook Endpoint**

The Stripe webhook endpoint handles events, such as successful payments, enabling real-time processing of orders and updates.

1. **Set Up API Route**: Create an API route in your application (e.g., `/api/webhook`) to receive webhook events from Stripe.
2. **Webhook Handler Overview**:
   * The handler verifies incoming requests using the Stripe webhook secret, ensuring secure event processing.
   * The handler can process various event types, such as `checkout.session.completed`, to perform actions like logging transactions or adding customers as collaborators in GitHub repositories.

**Example Environment Variables**:

Add the following keys to your environment configuration:

```bash
STRIPE_SECRET_KEY=your_stripe_secret_key
STRIPE_WEBHOOK_SECRET=your_stripe_webhook_secret
```

### **Feature Flag Setup**

To use Stripe with SSK-Pro, ensure the following feature flag is enabled in your `.env` file:

```bash
FF_STRIPE="true"
```

With this flag set, export the webhook in your app’s `/api/webhook` endpoint, and SSK-Pro will handle the integration seamlessly.

### **Additional Notes**

* **Security**: Stripe’s webhook signature verification ensures only authentic requests are processed.
* **GitHub Integration**: Your webhook handler can automate tasks, such as adding users to repositories upon purchase, enhancing user experience.

For further information on configuring Stripe’s webhook, refer to their [official documentation](https://stripe.com/docs/webhooks).


# Implementing in Your Project

Chapter 3: Implementing in Your Project

## **Step 5 - Environment Configuration**

Ensure all necessary environment variables are set in your `.env` file:

```bash
STRIPE_SECRET_KEY=sk_test_your_secret_key
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret
```

These variables are crucial for authenticating with Stripe and GitHub.

## Step 6 - Register the Webhook Endpoint

### In Stripe Dashboard:

1. Go to **Developers > Webhooks**.
2. Click **Add endpoint**.
3. Enter your live webhook endpoint URL (e.g., `https://yourdomain.com/api/webhook`).

### Select Events:

* Choose the events you want Stripe to send to your endpoint, such as `checkout.session.completed`.

***

## Step 7 - Test the Webhook

To ensure everything is set up correctly:

### Run Your Application Locally:

Start your development server.

### Use Stripe CLI:

1. **Install the Stripe CLI**.
2. Run the following command to forward events to your local webhook endpoint:

```bash
stripe listen --forward-to localhost:4200/api/webhook
```

### **Simulate Events:**

* Use the CLI or Stripe Dashboard to trigger test events.
* Verify that the webhook receives the events and processes them correctly.

### Review Logs:

Check your application logs to ensure there were no errors during the process.

## Final Notes

### Code Comments:

The webhook.ts file includes comprehensive comments explaining each part of the webhook handling process. Customers are encouraged to read these comments to gain a deeper understanding.

### Customization:

* You can modify the webhook logic to suit your specific needs.
* Consider adding error handling, logging, or additional features as required.

### Security:

* Keep your API keys and tokens secure.
* Do not commit them to version control or expose them publicly.

**Congratulations! You have successfully integrated Stripe into your SSK-Pro project.**


# Lemon Squeezy

This guide provides a comprehensive overview of integrating **Lemon Squeezy** into your **SSK-Pro** project. With Lemon Squeezy, you can seamlessly manage payments, handle affiliate marketing, and securely track order events.

***

## **Overview**

The Lemon Squeezy integration in **SSK-Pro** includes:

* **Payment Processing**: Receive and process payments with Lemon Squeezy.
* **Affiliate Marketing**: Support for Lemon Squeezy's built-in affiliate marketing, allowing you to incentivize referrals.
* **Webhook Handling**: Automatically receive events like `order_created` and securely store relevant data in your database.
* **Feature Flag Flexibility**: Use environment-controlled feature flags to toggle Lemon Squeezy and other payment providers (e.g., Stripe).

***

## **Prerequisites**

Before starting, make sure you have the following:

* **LEMONSQUEEZY\_WEBHOOK\_SECRET** environment variable (up to 40 characters). This secret is crucial for verifying the authenticity of incoming Lemon Squeezy events.
* **Environment Feature Flags**:
  * `FF_LEMON="true"` to enable Lemon Squeezy.
  * `FF_LEMON_SQUEEZY_AFFILIATES="true"` to enable Lemon Squeezy affiliate marketing.
  * Ensure `FF_STRIPE="false"` if using Lemon Squeezy to avoid conflicts with Stripe.

***

## **Getting Started**

Follow these chapters to configure and integrate Lemon Squeezy into your **SSK-Pro** project:

For further details on Lemon Squeezy’s webhook specifications, refer to their [official documentation](https://docs.lemonsqueezy.com/). This guide ensures that your integration is secure, flexible, and fully aligned with **SSK-Pro**'s feature flag system, giving you control over your payment provider setup.


# Setting Up Lemon Squeezy Account

Chapter 1: Setting Up Your Lemon Squeezy Account

## **Step 1 - Create a Lemon Squeezy Account**

1. **Sign Up**: Visit [Lemon Squeezy](https://lemonsqueezy.com) and create an account if you don’t already have one.
2. **Dashboard Access**: After setting up your account, log in to access the Lemon Squeezy Dashboard.

## **Step 2 - Obtain Webhook Secret**

1. **Navigate to Webhooks**: In the Lemon Squeezy Dashboard, locate the **webhooks** section under your account settings.
2. **Create Webhook**:
   * Add a webhook URL to handle events (e.g., `https://yourdomain.com/api/webhook`).
   * Select the relevant events, such as `order_created`.
3. **Copy the Webhook Secret**: This secret is essential for signature verification.
4. **Add to Environment Variables**: In your project’s `.env` file, add:

   ```bash
   LEMONSQUEEZY_WEBHOOK_SECRET=your_webhook_secret
   ```

## **Step 3 - Enable Lemon Squeezy Integration with Feature Flags**

SSK-Pro allows you to toggle payment providers via feature flags. Set the Lemon Squeezy feature flag in your `.env` file to enable this integration.

```bash
FF_LEMON="true" # Enables Lemon Squeezy
FF_LEMON_SQUEEZY_AFFILIATES="true" # Enables Lemon Squeezy Affiliates
FF_STRIPE="false" # Disables Stripe if using Lemon Squeezy
```

For consistency and to prevent conflicts, only one payment provider (Stripe or Lemon Squeezy) should be enabled.


# Configuring the Webhook Endpoint

Chapter 2: Implementing Lemon Squeezy Webhook in Your Application

## **Step 4 - Configure the Webhook Endpoint**

The Lemon Squeezy webhook endpoint processes events such as new orders, verifies their authenticity, and stores them in the database. This section will guide you through creating and configuring this endpoint in your application.

### **1. Set Up API Route**

Create an API route, for example, `/api/webhook`, to handle incoming webhook events from Lemon Squeezy. Ensure that this route is secure and configured correctly to handle Lemon Squeezy events.

### **2. Webhook Handler Overview**

Your webhook handler should:

* **Process Incoming Requests**: It verifies the Lemon Squeezy signature, ensuring the event’s authenticity and security.
* **Signature Verification**: Use the `LEMONSQUEEZY_WEBHOOK_SECRET` environment variable to generate an HMAC digest. Compare it with the incoming request signature using a timing-safe method for secure validation.
* **Order Data Handling**: When an `order_created` event is received, the handler can securely extract and save order details in your database.

### **Additional Notes**

* **Feature Flag Configuration**: Ensure Lemon Squeezy is enabled in your `.env` file with `FF_LEMON="true"`. This helps toggle the payment provider without modifying the core code, allowing flexibility across environments.
* **Security**: Signature verification is essential to ensure that only authentic requests from Lemon Squeezy are processed.
* **Database Integration**: Configure your handler to store specific details from each order event, including product name, amount, and user information.

For additional information on Lemon Squeezy’s webhook specifications, refer to their [official documentation](https://docs.lemonsqueezy.com/).


# Testing and Verifying Integration

Chapter 3: Testing and Verifying Your Implementation

## **Step 4 - Verify Webhook Integration**

### Local Testing

1. **Run Your Application Locally**: Start your development server to test webhook handling.
2. **Simulate Webhook Events**:
   * Use a tool like [ngrok](https://ngrok.com/) to expose your local server to the internet.
   * Add the ngrok URL as your webhook URL in Lemon Squeezy and simulate events to verify that they’re correctly received.

### Check Logs

* Review application logs to confirm the `POST` handler processes events and verifies signatures as expected.

***

## Final Notes

### Code Comments

The `webhook.ts` file includes comments explaining each part of the webhook handling process. Customers are encouraged to read these comments to understand the implementation.

### Security Considerations

* Ensure your **LEMONSQUEEZY\_WEBHOOK\_SECRET** is securely stored and never exposed in your codebase or logs.

### Customization

* Modify webhook logic to fit your requirements. You may add error handling, logging, or extra features as needed.

**Congratulations! You have successfully integrated Lemon Squeezy into your SSK-Pro project.**


# Affiliate Marketing

Affiliate Marketing Guide for SSK Pro

Ready to tap into the power of your network and turn your customers into unstoppable advocates? **SSK-Pro** gives you everything you need to kickstart and scale your affiliate marketing efforts. Whether you're after simplicity or full-on customization, we’ve got your back. The magic duo? **Lemon Squeezy** and **Rewardful**—each offering unique perks to supercharge your business growth.

***

## **Why Go All-In on Affiliate Marketing?**

Affiliate marketing isn’t just a buzzword—it’s a proven way to boost your revenue and make your customers part of your success story. Turn fans, partners, and users into passionate brand advocates. You win, they win, everybody wins. Cha-ching! 💰

***

## **Choose Your Secret Sauce with SSK-Pro:**

* **🍋 Lemon Squeezy**: Keep things simple, slick, and cost-effective with no monthly fees and a pay-as-you-go model. Perfect for startups and small projects who want easy wins.
* **🌟 Rewardful**: Scale like a pro with flat monthly fees, tailored affiliate campaigns, and data-driven insights. Built for those ready to dominate the market.

***

Ready to dive deeper? Check out the guides for **Lemon Squeezy** and **Rewardful** to find the perfect match for your affiliate strategy and start turning connections into cash.


# Lemon Squeezy

Want to turbocharge your sales without the hassle? **Lemon Squeezy** makes affiliate marketing ridiculously simple—no complex setups, no monthly fees. Turn your customers and fans into unstoppable sales machines and watch your business thrive!

***

## **Why Pick Lemon Squeezy?**

* **Super Simple Setup**: Get your affiliate program off the ground in minutes.
* **No Monthly Bills**: Pay a small cut of each sale—no expensive monthly fees weighing you down.
* **One-Stop Shop**: Payments, subscriptions, and affiliate tracking all under one roof.
* **Automatic Payouts**: Focus on growing your business while your affiliates get paid like clockwork.

***

## **How to Get Started with Lemon Squeezy Affiliates**

### **1. Configure Environment Variables**

To set up Lemon Squeezy's affiliate tools, add these variables to your `.env` file:

```bash
NEXT_PUBLIC_AFFILIATE_LOGIN_LEMON="https://your-lemon-login-url"
NEXT_PUBLIC_AFFILIATE_SIGNUP_LEMON="https://your-lemon-signup-url"
```

These URLs will guide affiliates to easily sign up and access their accounts, making it simple for them to promote your products.

### **2. Set Up Your Affiliate Links**

Provide seamless access to sign-ups and logins for your affiliates using the URLs you configured.

### **3. Automate Commissions**

Set it up once, and let Lemon Squeezy handle everything. Your affiliates get rewarded, you enjoy higher revenue, and it all works like magic.

### **4. Track and Optimize**

Use built-in tools to monitor affiliate performance, fine-tune your campaigns, and maximize results.

***

Ready to unleash your affiliate power? **Lemon Squeezy** keeps things smooth, simple, and set for success. Let’s make it rain sales! 🍋💥


# Rewardful

Scale your affiliate marketing like a pro with **Rewardful**! Seamlessly integrated with **Stripe**, Rewardful gives you all the tools you need to create, track, and optimize affiliate campaigns, driving your business to new heights.

***

## **Why Choose Rewardful?**

* **Flat Monthly Fees**: Enjoy predictable pricing that makes scaling easy and cost-effective.
* **Customizable Campaigns**: Craft affiliate incentives and tailor campaigns to suit your growth goals.
* **Data-Driven Insights**: Leverage powerful analytics to optimize and boost affiliate performance.

***

## **How Rewardful Works**

**Rewardful** lets you maximize the power of your affiliate network with precision and customization. Set flexible commissions, track every sale, and reward your affiliates—all while benefiting from deep integration with **Stripe** for streamlined payment processing.

***

## **Get Started with Rewardful**

### **1. Configure Environment Variables**

To integrate Rewardful into your project, add these variables to your `.env` file:

```bash
NEXT_PUBLIC_REWARDFUL_API_KEY="your-rewardful-api-key"
NEXT_PUBLIC_AFFILIATE_LOGIN_REWARDFUL="https://your-rewardful-login-url"
NEXT_PUBLIC_AFFILIATE_SIGNUP_REWARDFUL="https://your-rewardful-signup-url"
```

These variables ensure your affiliates can easily sign up, log in, and access your program, while enabling seamless integration with Rewardful’s powerful tools.

### **2. Integrate with Stripe**

Rewardful’s integration with **Stripe** makes it easy to manage payments and attribute commissions to your affiliates. Ensure your Stripe account is connected for full functionality.

### **3. Create Custom Campaigns**

Design and launch affiliate campaigns tailored to your business strategy:

* Set commission rates.
* Create custom incentives to motivate your affiliates.
* Track and analyze campaign performance.

### **4. Monitor and Optimize**

Gain insights into affiliate performance through Rewardful’s analytics dashboard. Use data-driven decision-making to refine and grow your network.

***

## **Tips for Success**

* **Keep Your Keys Secure**: Ensure API keys and other sensitive data are kept private.
* **Test Before Launch**: Use a sandbox or staging environment to validate your setup.
* **Maximize Affiliate Engagement**: Communicate frequently, offer compelling incentives, and optimize your campaigns based on performance data.

***

Harness the full power of affiliate marketing with **Rewardful**—make every connection count and every campaign a success! 🌟


# Form and reCAPTCHA

reCAPTCHA Integration Guide for SSK Pro

This guide walks you through setting up **reCAPTCHA** on your forms for added security and spam prevention. The integration is simplified with **SSK**'s built-in Form component, which handles toast notifications, reCAPTCHA, and form validation using server actions.


# Setting Up reCAPTCHA

Chapter 1:

## Step 1: **Sign Up for Google reCAPTCHA**

1. Go to the [Google reCAPTCHA Admin Console](https://www.google.com/recaptcha/admin).
2. Register your site by adding your domain (e.g., `localhost` for development and your production domain).
3. Choose **reCAPTCHA v3**.
4. Copy the **Site Key** and **Secret Key**.

## Step 2: **Add Keys to Your Environment**

1. Open your `.env` file and add the keys:

```bash
NEXT_PUBLIC_RECAPTCHA_SITE_KEY=your_site_key
RECAPTCHA_SITE_SECRET=your_secret_key
```

## Step 3 - Whitelisting Domains

In your backend, ensure that the domains allowed to submit forms are whitelisted. The SSK Form Component provides this by default for production and development environments.

```tsx
const WHITE_LISTED_HOSTNAMES = [
  'localhost',
  'yourdomain.com',
  'www.yourdomain.com',
]
```

This prevents tokens from untrusted sources from being processed.


# Integrating reCAPTCHA with Forms

Chapter 2:

## Step 4: **Frontend Setup with the SSK Form Component**

The **SSK Form Component** is a powerful, easy-to-integrate solution for handling forms in your application. It simplifies form validation, reCAPTCHA integration, and submission feedback, allowing you to focus on building user experiences rather than handling form logic.

### Key Features:

* **Automatic reCAPTCHA Validation**: The form integrates reCAPTCHA validation to ensure submissions are secure and genuine.
* **Seamless Feedback with Toast Notifications**: Instant feedback is provided to the user via toast notifications, ensuring they know if the form was successfully submitted or if issues arise.
* **Built-in Form Validation**: Automatically handles form validation on the server, removing the need for extra manual checks.

### How It Works:

The SSK Form Component seamlessly handles form submissions, integrates validation processes, and supports custom actions. Once a form is submitted successfully, you can direct users to a custom success page or trigger a success notification. Additionally, it offers a flexible structure where you can easily add custom fields, buttons, and form logic tailored to your needs.

* The form’s state is managed for you, allowing easy access to form data and state throughout the submission process.
* **Dynamic Integration**: Simply wrap your form elements with the **SSK Form Component**, and you’re good to go. No need to manually manage validation, reCAPTCHA, or feedback mechanisms.

### Example Usage:

1. **Set Up**: Add the form component to your page and pass it necessary props such as form ID, action, and any success redirect URL.
2. **Custom Fields**: Use child components to customize how the form fields are rendered, passing the form state for easy integration.
3. **Success Handling**: After form submission, the component can redirect users or display success messages, based on your configuration.

***

This version streamlines the explanation for clarity, highlighting the features that make the SSK Form Component easy to implement and beneficial for developers. Let me know if you need further adjustments or if there's anything more you'd like to focus on!


# Verifying reCAPTCHA on the Backend

Chapter 3:

## Step 5 - Backend Verification

The **SSK Form Component** handles backend reCAPTCHA token verification through server actions. When the form is submitted, the reCAPTCHA token is sent to the backend, where it's validated automatically.

To verify the token, ensure your backend environment has the necessary reCAPTCHA keys configured. You will need to call the `verifyRecaptcha` function within your server action handling the form submission, like this:

```typescript
await verifyRecaptcha(formData.get('token'))
```

This function securely processes and validates the token, ensuring that the submission meets reCAPTCHA's security criteria.


# Environment Variables for reCAPTCHA

Chapter 4:

## Step 6 - Test Your Form with reCAPTCHA

After integrating reCAPTCHA via the SSK Form Component, ensure it's working as expected by following these steps:

1. **Run your local server**\
   Ensure your local server is running with the correct `.env` variables loaded.
2. **Submit the Form**\
   Submit the form through your frontend, and verify that the reCAPTCHA validation occurs.
3. **Use reCAPTCHA Test Tool**\
   Use the [Google reCAPTCHA Testing Tool](https://developers.google.com/recaptcha/docs/faq) to simulate user interactions and verify that the form works as expected.

## Step 7 - Debugging

If reCAPTCHA is not working, check:

* The **reCAPTCHA score** (recommend > 0.7).
* Ensure that the domains in the **whitelist** are correct.


# Email Integration with Nodemailer

Email Integration Guide for SSK-Pro

This section provides a detailed guide on integrating **Nodemailer** for handling various email functionalities in **SSK-Pro**, including contact requests, email verification, and error handling.

With **Nodemailer**, you can also send custom emails as notifications to your team or to customers, making it an essential tool for both internal communications and customer engagement.


# Setting Up Email Server

Chapter 1:

## Step 1 - Set Up Environment Variables

To send emails, you need to configure your environment variables. In the root of your project, create or update the `.env` file with the following values:

```bash
EMAIL_SERVER_HOST=smtp.your-email-provider.com
EMAIL_SERVER_PORT=587
EMAIL_SERVER_USER=your-email@domain.com
EMAIL_SERVER_PASSWORD=your-email-password
FULL_URL=https://your-domain.com
```

These environment variables are required to connect to your SMTP email service and define your application’s base URL.

Make sure to replace the placeholder values with the actual credentials provided by your email service provider.


# Sending Contact Requests

Chapter 2:

## Step 2 - Use Nodemailer to Send an Email

To send emails, the `sendEmail` function in **SSK-Pro** allows you to send emails through your configured SMTP server.

```typescript
await sendEmail({
  to: 'recipient@example.com',
  from: 'noreply@yourdomain.com',
  subject: 'Test Email',
  text: 'This is a test email.',
})
```

This function is pre-configured to use the email server defined in your environment variables. You can customize the email’s recipient, sender, subject, and body content.


# Authentication

Authentication with NextAuth, Prisma, and the New App Router

## Introduction

This project configures **NextAuth.js** to store user sessions via **Prisma** in a relational database (because sometimes you need a safe place for all those cookies and tokens). The new **Next.js App Router** is utilized for a cleaner approach to rendering on both the client and the server. If you like the old Pages Router, that’s fine too, but the future is here and it’s, well, new.

## Why Prisma for Sessions?

Prisma takes the guesswork out of database interactions. Instead of cobbling together SQL queries in every corner of your code, you define a schema that NextAuth can hook into. This way, session data (and user data) is stored reliably in your own database, rather than ephemeral memory or a single giant cookie that might vanish if a strong breeze hits your browser.

## The General Setup

You’ll need to install the usual suspects:

* `next-auth` for authentication
* `prisma` (and the Prisma client) for database interactions
* `@auth/prisma-adapter` (the official NextAuth-Prisma adapter)

Once those are in place, you configure NextAuth to point at **Prisma** as its session storage mechanism. That means no more fuss with JWT-based session strategies—database-backed sessions keep you covered.

## Environment Variables

Keep your credentials private by placing them in a `.env` file or your hosting provider’s environment settings:

* `DATABASE_URL` for your Prisma connection
* `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` for Google OAuth (if you’re using it)
* `NEXTAUTH_SECRET` for production security

**Pro Tip:** Don’t push these secrets to a public repo—unless you really want random people logging in as you.

## The New App Router

Next.js introduced a fancy new approach to routing and rendering. Rather than relying on the standard `pages` directory for your API endpoints, you can define **server-side**, **client-side**, and **shared** components in the `app` directory.

* **Server Components / Actions**: Perfect for querying or mutating user data (like checking who is logged in) without shipping all that logic to the client.
* **Client Components**: Great when you need immediate user interactions, such as a “Sign In” or “Sign Out” button that triggers NextAuth’s client methods.

## Getting the Session

To check if someone is logged in on the server, you can call a helper method (e.g., `getSession()`) that wraps NextAuth’s `getServerSession`. No need to bring all your NextAuth config into every single route—just point to an `authOptions` object that sets up your providers, your Prisma adapter, and your session strategy.

On the client side, import the NextAuth React hook `useSession()` to see who’s there. If `useSession()` returns `null`, that means no one’s logged in; if it returns a user, you know exactly who’s behind that keyboard.


# Auth with Google

Below are three separate Markdown files based on the original content. You can name them intro.md, providers.md, and auth0.md to keep your documentation organized. Each file contains only the relevant sections of the guide.

intro.md

## NextAuth + Prisma + New App Router

### Introduction

This project configures **NextAuth.js** to store user sessions via **Prisma** in a relational database (because sometimes you need a safe place for all those cookies and tokens). The new **Next.js App Router** is utilized for a cleaner approach to rendering on both the client and the server. If you like the old Pages Router, that’s fine too, but the future is here and it’s, well, new.

### Why Prisma for Sessions?

Prisma takes the guesswork out of database interactions. Instead of cobbling together SQL queries in every corner of your code, you define a schema that NextAuth can hook into. This way, session data (and user data) is stored reliably in your own database, rather than ephemeral memory or a single giant cookie that might vanish if a strong breeze hits your browser.

### The General Setup

You’ll need to install the usual suspects:

* `next-auth` for authentication
* `prisma` (and the Prisma client) for database interactions
* `@auth/prisma-adapter` (the official NextAuth-Prisma adapter)

Once those are in place, you configure NextAuth to point at **Prisma** as its session storage mechanism. That means no more fuss with JWT-based session strategies—database-backed sessions keep you covered.

### Environment Variables

Keep your credentials private by placing them in a `.env` file or your hosting provider’s environment settings:

* `DATABASE_URL` for your Prisma connection
* `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` for Google OAuth (if you’re using it)
* `NEXTAUTH_SECRET` for production security

**Pro Tip:** Don’t push these secrets to a public repo—unless you really want random people logging in as you.

### The New App Router

Next.js introduced a fancy new approach to routing and rendering. Rather than relying on the standard `pages` directory for your API endpoints, you can define **server-side**, **client-side**, and **shared** components in the `app` directory.

* **Server Components / Actions**: Perfect for querying or mutating user data (like checking who is logged in) without shipping all that logic to the client.
* **Client Components**: Great when you need immediate user interactions, such as a “Sign In” or “Sign Out” button that triggers NextAuth’s client methods.

### Getting the Session

To check if someone is logged in on the server, you can call a helper method (e.g., `getSession()`) that wraps NextAuth’s `getServerSession`. No need to bring all your NextAuth config into every single route—just point to an `authOptions` object that sets up your providers, your Prisma adapter, and your session strategy.

On the client side, import the NextAuth React hook `useSession()` to see who’s there. If `useSession()` returns `null`, that means no one’s logged in; if it returns a user, you know exactly who’s behind that keyboard.

providers.md

## Google & Other Providers

### Overview

NextAuth supports a wide range of OAuth providers, including but not limited to:

* Google
* GitHub
* Facebook
* Twitter
* Apple
* Auth0 (covered in more detail in a separate page)

This gives you the flexibility to let users sign in with the accounts they already have, simplifying onboarding. Below, we’ll focus on **Google** as an example, but the process is similar for most providers.

### Setting Up Google OAuth

1. Head to the [Google Cloud Console](https://console.cloud.google.com).
2. Create or select a project, then enable the **OAuth consent screen** and **OAuth credentials**.
3. Grab your **Client ID** and **Client Secret**.
4. Add them to your `.env` file as `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`:

```env
GOOGLE_CLIENT_ID="your-google-client-id.apps.googleusercontent.com"
GOOGLE_CLIENT_SECRET="your-google-client-secret"
```

5. In your NextAuth configuration (where you define authOptions), add the Google provider:

```typescript
import GoogleProvider from 'next-auth/providers/google'

providers: [
  GoogleProvider({
    clientId: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
  }),
  // ...other providers
]
```

That’s it! Now your users can sign in with their Google accounts.

Other Providers

Most providers require you to: 1. Create or configure an application in their developer portal. 2. Retrieve Client ID/Secret or keys. 3. Plug these credentials into your NextAuth config—similar to Google.

For a list of officially supported providers, check the NextAuth Providers docs.

Example Usage with getSession() and useSession()

1. Server: Checking the Session

Here’s a minimal example of how you might use getSession() (or getServerSession()) in a Server Component (e.g., app/dashboard/page.tsx). This example assumes you’ve got a helper function that returns getServerSession(authOptions):

// app/dashboard/page.tsx (Server Component) import { getSession } from '@/path/to/your/auth-helper'

export default async function DashboardPage() { const session = await getSession()

if (!session) { // If no session, you could redirect to the sign-in page or throw an error return

You need to sign in to access the dashboard.

}

return (

## Welcome, {session.user?.email}!

Only signed-in users can see this content.

) }

What’s happening here? • getSession() internally calls getServerSession(authOptions) from NextAuth. • If there’s no session, we show a friendly message (or redirect). • If the user is signed in, we display their email.

2. Client: Displaying Sign-In State

Below is a Client Component example ("use client") showing how useSession() can display a “Sign In” button or user info:

"use client" import { signIn, signOut, useSession } from "next-auth/react"

export default function AuthStatus() { const { data: session, status } = useSession()

if (status === 'loading') { // Session data is loading, you can show a spinner here return

Loading...

}

if (!session) { // No session found, show a button to sign in return ( \<button onClick={() => signIn("google")}> Sign In with Google ) }

// If we got here, the user has a session return (

Welcome, {session.user?.email}

\<button onClick={() => signOut()}>Sign Out) }

Highlights: • useSession() returns session data if available, or null if not. • You can pass a provider to signIn() (like "google") for immediate OAuth flows. • signOut() kills the session in the database (assuming you’re using the database strategy) and logs the user out.


# Implement Auth0

Auth0 is another popular provider that supports enterprise-level features like single sign-on, passwordless logins, and a robust rules engine. Integrating it with NextAuth is straightforward.

## Steps to Integrate Auth0

1. **Create an Auth0 Application**
   * Sign in to [Auth0 Dashboard](https://manage.auth0.com).
   * Create a new application under the **Applications** section (choose "Regular Web App").
2. **Retrieve Credentials**
   * Under your Auth0 application settings, you’ll find **Client ID**, **Client Secret**, and **Domain** (sometimes referred to as `issuer` in NextAuth).
3. **Add Environment Variables**

```env
AUTH0_CLIENT_ID="your-auth0-client-id"
AUTH0_CLIENT_SECRET="your-auth0-client-secret"
AUTH0_ISSUER="https://your-tenant-id.auth0.com"
```

```
4.	Configure the Auth0 Provider in NextAuth
```

import Auth0Provider from 'next-auth/providers/auth0'

providers: \[ Auth0Provider({ clientId: process.env.AUTH0\_CLIENT\_ID, clientSecret: process.env.AUTH0\_CLIENT\_SECRET, issuer: process.env.AUTH0\_ISSUER, }), // ...other providers ]

```
5.	Redirects & Allowed URLs
```

In your Auth0 application settings, ensure your allowed callback/logout URLs match your app’s domain. For local development, you might add something like:

<http://localhost:3000/api/auth/callback/auth0>

as an allowed callback URL.

```
6.	Test Your Integration
•	Head to your sign-in page or wherever you trigger signIn('auth0').
•	Upon success, you should be redirected back to your Next.js site with the user session now stored in your Prisma-backed database.
```

Auth0 Benefits • Advanced Security & Enterprise Options: Great for companies that need SSO, multi-factor authentication, or specialized compliance. • Customizable Login Pages: Tailor your login experience to match your brand. • Rules & Hooks: Insert custom logic during the Auth flow (e.g., for user metadata).

That’s it! You now have a secure integration with Auth0. For more advanced options like Role-Based Access Control or multi-tenant setups, refer to the Auth0 Docs.

***

### Final Thoughts

With these three separate files:

* **`intro.md`** covers the overall NextAuth + Prisma + Next.js setup.
* **`providers.md`** explains how to integrate Google and other common OAuth providers, plus shows code examples for getting the session.
* **`auth0.md`** focuses on setting up Auth0 specifically, including environment variables and callback URLs.


# SSK-License

**Effective Date**: September 19, 2024

This Software License Agreement ("Agreement") governs the use of the Startup Starter Kits (SSK-Core and SSK-Pro), hereafter referred to as "Software," created and provided by TTC Three Tech Consulting LTD, hereafter referred to as "Licensor."

By purchasing, downloading, installing, or otherwise using the Software, you ("Licensee") agree to be bound by the terms of this Agreement.

***

## 1. License Grant

Licensor grants you a non-exclusive, non-transferable, limited **perpetual** license to use the Software for your personal or internal business purposes only. You may not distribute, resell, share, or sublicense the Software to any third party.

***

## 2. Scope of Use

* You may use the Software to build one or multiple internal business projects, but this license is tied to you or your organization only.
* Modifications to the Software are allowed for internal use only. Modified versions of the Software are subject to the same restrictions as the original.
* This license does not extend to contractors or external users. Each user or organization must purchase their own license to use the Software.

***

## 3. Prohibited Uses

Licensee agrees that the Software and any derivative works:

* May not be used to create, distribute, or sell derivative products that compete with page-builder tools, templates, or similar software.
* May not be used to build or create any templates, page-builder tools, website-building platforms, or any similar service or product for commercial use or distribution.
* May not be redistributed, sublicensed, or shared, in original or modified form, with any third parties.
* May not be used to build a competing product or service in any form.

***

## 4. No Redistribution or Resale

You may not rent, lease, lend, sell, redistribute, or sublicense the Software. The Software may only be used by the original purchaser and may not be transferred to any other individual or entity.

***

## 5. Intellectual Property

All rights, title, and interest in and to the Software, including any derivative works or modifications, remain with Licensor. Licensee acquires no rights in the Software other than as expressly set forth in this Agreement.

Licensor represents and warrants that the Software does not infringe any third-party intellectual property rights.

***

## 6. Updates and Support

Licensor may, at its sole discretion, provide updates, upgrades, or new features to the Software from time to time. However, Licensor is under no obligation to provide such updates or to continue supporting the Software. Any updates provided are non-transferable and available only to the original purchaser. Continued access to updates is contingent upon compliance with this Agreement and may require additional fees or a valid subscription.

***

## 7. No Refunds

All sales of the Software are final, and no refunds will be provided under any circumstances. Licensee is responsible for ensuring the suitability of the Software prior to purchase. No refunds will be provided under any circumstances, including but not limited to dissatisfaction with the product or accidental purchases.

***

## 8. Termination

This license will automatically terminate if you fail to comply with any of its terms. Upon termination, you must cease all use of the Software and destroy any copies in your possession.

***

## 9. License Key

The Software may require a license key for activation. Licensee agrees not to share, distribute, or bypass any license key restrictions. Any attempts to circumvent the license key system will result in immediate termination of the license.

***

## 10. License Verification

Licensor reserves the right to audit the use of the Software to ensure compliance with this Agreement. Licensee agrees to provide reasonable assistance and access to relevant information in the course of such audits. Failure to comply with such audit requests may result in immediate termination of the license.

***

## 11. Third-Party Software

The Software may include or be bundled with third-party software components, which are provided under separate license terms. Licensee agrees to comply with the license terms for any such third-party components. Licensor shall not be responsible for any third-party software included with the Software.

***

## 12. Confidentiality

The Licensee agrees that the Software, including any documentation, designs, or related information, constitutes confidential information of the Licensor. Licensee agrees not to disclose, share, or allow access to the Software to any third party without Licensor’s express written consent.

***

## 13. Indemnification

Licensee agrees to indemnify, defend, and hold Licensor harmless from and against any claims, damages, liabilities, and costs arising out of or related to the Licensee’s use or misuse of the Software, including violations of this Agreement.

***

## 14. Data Collection and Privacy

Licensor may collect and store technical and usage data related to the Licensee’s use of the Software for the purposes of improving the Software or enforcing compliance with this Agreement. Such data collection will be subject to Licensor’s Privacy Policy.

***

## 15. Disclaimer of Warranties

The Software is provided "as is" without any warranties of any kind, either express or implied. Licensor does not guarantee that the Software will be error-free or uninterrupted. All implied warranties, including but not limited to implied warranties of merchantability and fitness for a particular purpose, are expressly disclaimed.

***

## 16. Limitation of Liability

In no event shall Licensor be liable for any indirect, incidental, special, consequential, or punitive damages arising out of the use or inability to use the Software, even if advised of the possibility of such damages.

***

## 17. Governing Law

This Agreement shall be governed by and construed in accordance with the laws of Cyprus, without regard to its conflict of law principles.

***

## 18. Contact Information

For questions regarding this License Agreement, please contact:

TTC Three Tech Consulting LTD\
Email: <contact@threetech.consulting>\
Website: <https://threetech.consulting>


