### Create a Static Landing Page with SEO Components (JavaScript)
Source: https://shipfa.st/docs/-old/tutorials/static-page
This JavaScript code snippet demonstrates how to create a simple static landing page using ShipFast's components. It includes the use of `TagSEO` for meta tags and `TagSchema` for rich snippets to improve Google ranking. The example also shows how to apply a DaisyUI theme and structure basic content.
```javascript
import TagSEO from "@/components/TagSEO";
import TagSchema from "@/components/TagSchema";
export default function Landing() {
return (
<>
{/* 👇 Add all your SEO tags for the page (title, keywords, description, open graph etc...) */}
{/* 👇 Tells Google what type is your site. In this example, we could say it's a SoftwareApplication. It's used for Rich Snippets */}
Food recipes you'll love 🥦
Our AI will generate recipes based on your preferences. New recipes
will be added every week!
>
);
}
```
--------------------------------
### Adding SEO Tags to Next.js Page Component
Source: https://shipfa.st/docs/-old/features/seo
This snippet demonstrates how to include the TagSEO component in a Next.js page to set title and canonical slug for improved search engine optimization. It requires the TagSEO component to be imported and used within the page's JSX return statement. The component applies meta tags to the head section, enhancing page visibility on search engines like Google, with no additional dependencies beyond the project's setup.
```jsx
return (
<>
Tutorial
/>
)
```
--------------------------------
### Rendering Structured Data in Next.js Components
Source: https://shipfa.st/docs/features/seo
This code shows how to include structured data schema tags on a page to improve Google understanding and enable rich snippets. It uses the renderSchemaTags function from /libs/seo.js within a JSX component. No specific inputs beyond the function call; outputs are embedded schema tags in the HTML head. Limitation: Schema details must be defined in the seo.js library; relevant only for pages with applicable structured data like articles or products.
```javascript
import { renderSchemaTags } from "@/libs/seo";
export default function Page() {
return (
<>
{renderSchemaTags()}
Ship Fast
...
>
);
}
```
--------------------------------
### Install Rate Limiting Packages
Source: https://shipfa.st/docs/security/rate-limiting-api-routes
Installs the necessary Upstash Redis and Rate Limit packages for Node.js projects. These packages are essential for implementing API route protection.
```bash
npm install @upstash/redis @upstash/ratelimit
```
--------------------------------
### Create a Private User Dashboard Page with Next-Auth and MongoDB
Source: https://shipfa.st/docs/tutorials/private-page
This example demonstrates how to create a private user dashboard using Next.js App Router, Next-Auth for authentication, and MongoDB for user data storage. It fetches user data based on the session and displays it on the page, ensuring only authenticated users can access this information. Ensure you have configured Next-Auth and connected to MongoDB as per the project setup.
```javascript
import { getServerSession } from "next-auth";
import { authOptions } from "@/libs/next-auth";
import connectMongo from "@/libs/mongoose";
import User from "@/models/User";
export default async function Dashboard() {
await connectMongo();
const session = await getServerSession(authOptions);
const user = await User.findById(session.user.id);
return (
<>
User Dashboard
Welcome {user.name} 👋
Your email is {user.email}
>
);
}
```
--------------------------------
### Implement Sign-In Button with NextAuth in JavaScript
Source: https://shipfa.st/docs/-old/tutorials/user-auth
This JavaScript code defines a React component for a sign-in button that uses NextAuth's signIn function to initiate authentication. It requires NextAuth setup in the API and a config file defining the callbackUrl for post-login redirection to pages like /dashboard. Outputs a clickable button that triggers the sign-in process; limitations include dependency on NextAuth configuration and no handling for authentication errors in this component.
```javascript
1import { signIn } from "next-auth/react";
2import config from "@/config";
4const SigninButton = () => {
5 return (
6
12 );
13};
15export default SigninButton;
```
--------------------------------
### Custom SEO Metadata in Next.js Pages
Source: https://shipfa.st/docs/features/seo
This snippet demonstrates how to add custom SEO tags like title and canonical URL to a specific page without overriding all defaults. It relies on the getSEOTags function from /libs/seo.js, which integrates with Next.js metadata export. Inputs include title and relative canonical URL; outputs are SEO-optimized metadata for the page. Limitation: Requires updating each page individually for custom tags.
```javascript
import { getSEOTags } from "@/libs/seo";
...
export const metadata = getSEOTags({
title: "Terms and Conditions | ShipFast",
canonicalUrlRelative: "/tos",
});
export default async function TermsAndConditions() {
...
}
```
--------------------------------
### Create Private Dashboard with Next.js Authentication
Source: https://shipfa.st/docs/-old/tutorials/private-page
Implements a protected dashboard component using the usePrivate hook to enforce authentication and manage session state. Displays conditional user information and provides logout functionality via NextAuth.js. Requires authentication setup and the custom usePrivate hook from the hooks folder.
```jsx
import { useState } from "react";
import { signOut } from "next-auth/react";
import apiClient from "@/libs/api";
import { usePrivate } from "@/hooks/usePrivate";
import TagSEO from "@/components/TagSEO";
export default function Dashboard() {
// Custom hook to make private pages easier to deal with (see /hooks folder)
const [session, status] = usePrivate({});
const [isLoading, setIsLoading] = useState(false);
// Show a loader when the session is loading. Not needed but recommended if you show user data like email/name
if (status === "loading") {
return
Loading...
;
}
return (
<>
Your Food Recipes
{status === "authenticated"
? `Welcome ${session?.user?.name}`
: "You are not logged in"}
{session?.user?.email
? `Your email is ${session?.user?.email}`
: ""}
>
);
}
```
--------------------------------
### Add Custom Font in Layout.js (JavaScript)
Source: https://shipfa.st/docs/-old/components
This example demonstrates how to integrate a custom font from Google Fonts into the ShipFast project. It involves importing the desired font from `next/font/google` and then replacing the current font variable in the `Layout.js` file.
```javascript
import { Bricolage_Grotesque } from "next/font/google";
const font = Bricolage_Grotesque({ subsets: ["latin"] });
```
--------------------------------
### Protected User Profile Update API in Next.js
Source: https://shipfa.st/docs/tutorials/api-call
This functionality enables secure API calls from the client to update user data, using Next-Auth for session management and a MongoDB backend for persistence. The client-side component makes a POST request via an axios helper that handles errors and redirects, while the server-side route validates the session, connects to the database, and updates the user email. Dependencies include Next-Auth, Mongoose, and axios; inputs are user email, outputs are updated user data or error messages; limitations include requiring proper database configuration and session setup.
```javascript
"use client"
import { useState } from "react";
import apiClient from "@/libs/api";
const UserProfile = () => {
const [isLoading, setIsLoading] = useState(false);
const saveUser = async () => {
setIsLoading(true);
try {
const { data } = await apiClient.post("/user", {
email: "new@gmail.com",
});
console.log(data);
} catch (e) {
console.error(e?.message);
} finally {
setIsLoading(false);
}
};
return (
);
};
export default UserProfile;
```
```javascript
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/libs/next-auth";
import connectMongo from "@/libs/mongoose";
import User from "@/models/User";
export async function POST(req) {
const session = await getServerSession(authOptions);
if (session) {
const { id } = session.user;
const body = await req.json();
if (!body.email) {
return NextResponse.json({ error: "Email is required" }, { status: 400 });
}
try {
await connectMongo();
const user = await User.findById(id);
if (!user) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
user.email = body.email;
await user.save();
return NextResponse.json({ data: user }, { status: 200 });
} catch (e) {
console.error(e);
return NextResponse.json(
{ error: "Something went wrong" },
{ status: 500 }
);
}
} else {
// Not Signed in
return NextResponse.json({ error: "Not signed in" }, { status: 401 });
}
}
```
--------------------------------
### ButtonLead Component Integration for ShipFast (JavaScript)
Source: https://shipfa.st/docs/-old/tutorials/ship-in-5-minutes
This JavaScript code demonstrates how to integrate the ButtonLead component within different sections of a ShipFast landing page. It shows how to apply specific styling props like `extraStyle` for different use cases, such as the Hero/CTA sections versus the Pricing section. This component is used for main call-to-action buttons.
```javascript
import ButtonLead from "@/components/ButtonLead";
...
{/* For the Hero & CTA use this 👇 */}
{/* For the Pricing use this instead 👇 */}
...
```
--------------------------------
### Index Page Structure for ShipFast Landing Page (JavaScript)
Source: https://shipfa.st/docs/-old/tutorials/ship-in-5-minutes
This JavaScript code defines the main structure for the homepage of a ShipFast landing page. It imports various components like Header, Hero, Pricing, FAQ, CTA, and Footer, and renders them within a main content area. This serves as the entry point for the application.
```javascript
import Header from "@/components/Header";
import Hero from "@/components/Hero";
import Pricing from "@/components/Pricing";
import FAQ from "@/components/FAQ";
import CTA from "@/components/CTA";
import Footer from "@/components/Footer";
export default function Home() {
return (
<>
>
);
}
```
--------------------------------
### Homepage Structure in React (Next.js)
Source: https://shipfa.st/docs/tutorials/ship-in-5-minutes
Defines the main structure of the homepage for a Next.js application using React. It imports and renders various components like Header, Hero, Pricing, and Footer. The Suspense component is used for potential lazy loading of the Header.
```javascript
import { Suspense } from 'react'
import Header from "@/components/Header";
import Hero from "@/components/Hero";
import Problem from "@/components/Problem";
import FeaturesAccordion from "@/components/FeaturesAccordion";
import Pricing from "@/components/Pricing";
import FAQ from "@/components/FAQ";
import CTA from "@/components/CTA";
import Footer from "@/components/Footer";
export default function Home() {
return (
<>
>
);
}
```
--------------------------------
### Create SEO Landing Page with Next.js JavaScript
Source: https://shipfa.st/docs/tutorials/static-page
This code snippet shows how to build a simple static landing page in Next.js using ShipFast's SEO utilities and components. It sets up metadata for SEO, renders a hero section with title, description, image, and button. Requires Next.js framework and the custom @/libs/seo module; outputs a static page; limited to basic structure without dynamic data.
```javascript
import { getSEOTags } from "@/libs/seo";
export const metadata = getSEOTags({ canonicalUrlRelative: "/" });
export default function Landing() {
return (
<>
Food recipes you'll love 🥦
Our AI will generate recipes based on your preferences. New recipes
will be added every week!
>
);
}
```
--------------------------------
### Import Button Lead Component
Source: https://shipfa.st/docs/components/buttonLead
Demonstrates how to import and use the ButtonLead component in a Next.js application. The component automatically handles email collection and database storage through an API route.
```javascript
import ButtonLead from "@/components/ButtonLead";
```
--------------------------------
### Stripe Subscription Checkout Page (Next.js)
Source: https://shipfa.st/docs/tutorials/subscriptions
This component renders a checkout button for a Stripe subscription. It imports necessary components and configuration, sets the page to dynamic rendering, and displays a heading along with the checkout button, passing the subscription mode and price ID.
```javascript
1import ButtonAccount from "@/components/ButtonAccount";
2import ButtonCheckout from "@/components/ButtonCheckout";
3import config from "@/config";
4
5export const dynamic = "force-dynamic";
6
7export default async function Dashboard() {
8 return (
9
10
11
12
13
14 Subscribe to get access:
15
16
17
21
22
23 );
24}
25
```
--------------------------------
### Frontend API Call with Error Handling (React/JavaScript)
Source: https://shipfa.st/docs/-old/tutorials/api-call
This frontend code snippet demonstrates how to make a POST request to a user API endpoint using the provided `apiClient`. It includes state management for loading indicators and basic error handling to display messages from the backend. The `apiClient` is expected to be an Axios instance with pre-configured interceptors for base URL and error redirection.
```javascript
import { useState } from "react";
import apiClient from "@/libs/api";
const UserProfile = () => {
const [isLoading, setIsLoading] = useState(false);
const saveUser = async () => {
setIsLoading(true);
try {
const { data } = await apiClient.post("/user", {
email: "new@gmail.com",
});
console.log(data);
} catch (e) {
console.error(e?.message);
} finally {
setIsLoading(false);
}
};
return (
);
};
export default UserProfile;
```
--------------------------------
### Next-Auth Configuration for ShipFast
Source: https://shipfa.st/docs/tutorials/user-auth
The configuration file for NextAuth, located at `/app/api/auth/[...nextauth]/route.js`. This file is essential for setting up authentication providers and options within the ShipFast application.
```javascript
// /app/api/auth/[...nextauth]/route.js
// Configuration for NextAuth
```
--------------------------------
### Create Blocked Page for Rate Limited Users
Source: https://shipfa.st/docs/security/rate-limiting-magic-links
Defines the UI for the `/blocked` page, which is displayed to users who have exceeded the rate limit for magic link sign-ins. It provides options to try logging in again or return to the home page.
```javascript
"use client";
import config from "@/config";
import { signIn } from "next-auth/react";
import React from "react";
import Link from "next/link";
const Blocked = () => {
return (
Hm, Access Blocked
Try again in 1 minute
{" "}or{" "}
Home
);
};
export default Blocked;
```
--------------------------------
### Configure Theme in config.js (JavaScript)
Source: https://shipfa.st/docs/-old/components
This snippet shows how to configure themes within the `config.js` file. It involves setting the current theme and defining the main color based on the selected theme from `daisyui.themes`. Ensure at least one theme is always enabled.
```javascript
colors: {
theme: "YOUR_THEME",
main: themes[`[data-theme=YOUR_THEME]`]["primary"],
}
```
--------------------------------
### Import ButtonSignin in Javascript
Source: https://shipfa.st/docs/components/buttonSignin
Imports the ButtonSignin component from the specified path. This component is used for user sign-in and sign-up functionality, integrating with providers like Google and Magic Links to redirect users after login.
```javascript
1import ButtonSignin from "@/components/ButtonSignin";
```
--------------------------------
### Configure Security Headers in Next.js
Source: https://shipfa.st/docs/security/security-headers
Implements essential security headers including Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, and Referrer-Policy. These headers help protect against common web vulnerabilities like clickjacking and MIME type sniffing. The configuration applies to all routes using the async headers function in Next.js.
```javascript
const nextConfig = {
reactStrictMode: true,
images: {
domains: [
// NextJS component needs to whitelist domains for src={}
"lh3.googleusercontent.com",
"pbs.twimg.com",
"images.unsplash.com",
"logos-world.net",
],
},
async headers() {
return {
source: "/(.*)",
headers: [
{
key: "Strict-Transport-Security",
value: "max-age=31536000; includeSubDomains; preload",
},
{
key: "X-Frame-Options",
value: "DENY",
},
{
key: "X-Content-Type-Options",
value: "nosniff",
},
{
key: "Referrer-Policy",
value: "strict-origin-when-cross-origin",
},
],
};
}
};
module.exports = nextConfig;
```
--------------------------------
### Sign-in Button Component using Next-Auth
Source: https://shipfa.st/docs/tutorials/user-auth
A client component for a sign-in button that uses the `signIn` function from `next-auth/react` to initiate the authentication flow. It redirects the user to a callback URL specified in the application's configuration after a successful login.
```javascript
"use client"
import { signIn } from "next-auth/react";
import config from "@/config";
const SigninButton = () => {
return (
);
};
export default SigninButton;
```
--------------------------------
### Modal Component Usage (React/JavaScript)
Source: https://shipfa.st/docs/components/modal
Demonstrates how to use the Modal component within a React page. It manages the modal's open/closed state using useState. Assumes the Modal component is imported from '@/components/Modal'.
```javascript
1import Modal from "@/components/Modal";
2
3export default function Component() {
4 const [isModalOpen, setIsModalOpen] = useState(false);
5
6 return (
7
8 );
9}
```
--------------------------------
### Backend Protected API Endpoint with NextAuth (Node.js/JavaScript)
Source: https://shipfa.st/docs/-old/tutorials/api-call
This backend code snippet illustrates how to create a protected API endpoint (`/api/user.js`) using NextAuth for authentication and Mongoose for database interaction. It retrieves the user session, connects to MongoDB, and handles POST requests to update a user's email. It expects the session user ID to match the document ID for updates and includes basic request body validation.
```javascript
import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
import connectMongo from "@/libs/mongoose";
import User from "@/models/User";
export default async function handler(req, res) {
const session = await getServerSession(req, res, authOptions);
if (session) {
await connectMongo();
const { id } = session.user;
const { method, body } = req;
switch (method) {
case "POST": {
if (!body.email) {
return res.status(404).send({ error: "Email is needed" });
}
try {
const user = await User.findById(id);
if (!user) {
return res.status(404).json({ error: "User doesnt exists" });
}
user.email = body.email;
await user.save();
return res.status(200).json({ data: user });
} catch (e) {
console.error(e);
return res.status(500).json({ error: e?.message });
}
}
default:
res.status(404).json({ error: "Unknow request type" });
}
} else {
// Not Signed in
res.status(401).end();
}
}
```
--------------------------------
### Create Blocked Page Component
Source: https://shipfa.st/docs/security/rate-limiting-api-routes
A React component for the '/blocked' page, displayed when a user hits the API rate limit. It provides a message indicating access is blocked and offers options to log in again or return to the home page.
```javascript
"use client";
import config from "@/config";
import { signIn } from "next-auth/react";
import React from "react";
import Link from "next/link";
const Blocked = () => {
return (
Hm, Access Blocked
Try again in 1 minute
{" "}
or{" "}
Home
);
};
export default Blocked;
```
--------------------------------
### Configure API Route Rate Limiting Middleware (Javascript/Typescript)
Source: https://shipfa.st/docs/security/rate-limiting-api-routes
Sets up a middleware function in Next.js to rate limit incoming API requests. It uses Upstash Redis to track request counts and enforces a limit of 5 requests per minute per IP address. Requests exceeding the limit are redirected to a '/blocked' page.
```javascript
import { NextResponse } from "next/server";
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL,
token: process.env.UPSTASH_REDIS_REST_TOKEN,
});
const ratelimit = new Ratelimit({
redis: redis,
limiter: Ratelimit.slidingWindow(5, "60 s"),
});
export default async function middleware(request) {
const ip = request.ip ?? "127.0.0.1";
const { success } = await ratelimit.limit(ip);
return success
? NextResponse.next()
: NextResponse.redirect(new URL("/blocked", request.url));
}
export const config = {
matcher: ["/api/one", "/api/two"],
};
```
--------------------------------
### Configure Middleware for Rate Limiting Magic Links
Source: https://shipfa.st/docs/security/rate-limiting-magic-links
Sets up a Next.js middleware to rate limit requests to the magic link sign-in endpoint. It uses Upstash Redis to track request counts per IP address and redirects users to a blocked page if the limit is exceeded. The configuration limits to 5 requests per minute per IP.
```javascript
import { NextResponse } from "next/server";
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL,
token: process.env.UPSTASH_REDIS_REST_TOKEN,
});
const ratelimit = new Ratelimit({
redis: redis,
limiter: Ratelimit.slidingWindow(5, "60 s"),
});
export default async function middleware(request) {
const ip = request.ip ?? "127.0.0.1";
const { success } = await ratelimit.limit(ip);
return success
? NextResponse.next()
: NextResponse.redirect(new URL("/blocked", request.url));
}
export const config = {
matcher: ["/api/auth/signin/email"],
};
```
--------------------------------
### Implementing Modal Popup in Next.js React
Source: https://shipfa.st/docs/-old/components/modal
This snippet demonstrates a basic Modal component usage in a Next.js page, managing open/close state with React's useState hook. It requires the Modal component from '@/components/Modal' and React for hooks. Inputs include boolean isOpen and setter function; outputs a rendered popup. Limitation: Assumes daisyUI or similar for styling; no built-in animations shown.
```javascript
import Modal from "@/components/Modal";
export default function Component() {
const [isModalOpen, setIsModalOpen] = useState(false);
return (
);
}
```
--------------------------------
### Include Plausible Analytics Script in _document.js
Source: https://shipfa.st/docs/-old/features/analytics
This code snippet shows how to add the Plausible analytics script to the `_document.js` file in a Next.js project. It configures the script to use the proxied API endpoints defined in `next.config.js` and requires setting the `data-domain` attribute to your specific domain.
```javascript
```
--------------------------------
### Configure Next.js Rewrites for Plausible Analytics
Source: https://shipfa.st/docs/-old/features/analytics
This code snippet configures Next.js rewrites in `next.config.js` to proxy Plausible analytics scripts and API events. This is useful for bypassing adblockers that might block direct Plausible requests. It defines destinations for the Plausible script and event API.
```javascript
async rewrites() {
return [
{
source: "/plausible/js/script.js",
destination: "https://plausible.io/js/script.js",
},
{
source: "/plausible/api/event",
destination: "https://plausible.io/api/event",
},
];
}
```
--------------------------------
### Validate API Route Data with Zod in JavaScript
Source: https://shipfa.st/docs/security/schema-validation
This snippet demonstrates how to use the Zod schema validation library to validate incoming request data in a Next.js API route. It imports NextResponse from next/server and defines a schema that ensures the email field is a valid email string. The handler parses the request JSON, validates the email, returns a 400 error for invalid data, or returns the validated email on success.
```JavaScript
import { NextResponse } from "next/server";
import { z } from "zod";
const schema = z.object({
email: z.string().email(),
});
export async function POST(request) {
const { email } = await request.json();
const isValidEmail = schema.safeParse(email);
if (!isValidEmail.success) {
return NextResponse.json({ error: "Invalid email" }, { status: 400 });
}
return NextResponse.json({ email: isValidEmail.data });
}
```