Skip to content

[WIP] docs(example): Next - WooCommerce basic example #361

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions examples/next/woocommerce/.wp-env.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"phpVersion": "8.0",
"plugins": [
"https://github.com/wp-graphql/wp-graphql/releases/latest/download/wp-graphql.zip",
"https://github.com/AxeWP/wp-graphql-headless-login/releases/latest/download/wp-graphql-headless-login.zip",
"https://github.com/woocommerce/woocommerce/releases/latest/download/woocommerce.zip",
"https://downloads.wordpress.org/plugin/wpgraphql-ide.latest-stable.zip",
"https://github.com/wp-graphql/wp-graphql-woocommerce/releases/download/v0.21.2/wp-graphql-woocommerce.zip"
],
"themes": [
"https://downloads.wordpress.org/theme/storefront.latest-stable.zip"
],
"env": {
"development": {
"port": 8890
},
"tests": {
"port": 8891
}
},
"config": {
"WP_DEBUG": true,
"SCRIPT_DEBUG": false,
"GRAPHQL_DEBUG": true,
"WP_DEBUG_LOG": true,
"WP_DEBUG_DISPLAY": false,
"SAVEQUERIES": false
},
"mappings": {
"db": "./wp-env/db",
"wp-content/uploads": "./wp-env/uploads",
".htaccess": "./wp-env/setup/.htaccess"
},
"lifecycleScripts": {
"afterStart": "wp-env run cli -- wp rewrite structure '/%postname%/' && wp-env run cli -- wp rewrite flush"
}
}
164 changes: 164 additions & 0 deletions examples/next/woocommerce/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
# Next.js WooCommerce example - template hierarchy, data fetching and authentication with Apollo
This example demonstrates a complete headless WooCommerce solution with Next.js, showcasing essential e-commerce functionality including shopping cart management, checkout flow, and user authentication. Built with WordPress template hierarchy and modern data fetching patterns using both native fetch and Apollo Client.

## Features

- **E-commerce Core**: Add to cart, remove items, checkout process, and thank you page
- **Authentication**: Username/password login in headless WordPress environment
- **Template Hierarchy**: WordPress template system integration with Next.js
- **Data Fetching**: Dual approach with native fetch and Apollo Client
- **GraphQL Integration**: Powered by WPGraphQL, WPGraphQL Headless Login, and WooGraphQL plugins

## Screenshots

After following the installation steps, you should have the example webpage as shown in the screenshots below:

| | |
| :---------------------------------------------: | :--------------------------------------------------------: |
| ![login](./screenshots/login.png)<br>Login page | ![logged](./screenshots/logged.png "Posts")<br>After login |

## Project Structure

```
.
├── example-app/ # Next.js application folder containing frontend code
│ └── src/
│ ├── components/ # Reusable React components
│ ├── lib/ # Apollo Client configuration, client and helpers
│ └── pages/ # Next.js page routes
│ └── wp-templates/ # Next.js WordPress template hierarchy
├── .wp-env.json # wp-env configuration file
└── wp-env
└── db
└── database.sql # WordPress database including all demo data for the example
```

## Quick Start with wp-env

### Prerequisites

- Node.js (v18+ recommended)
- [Docker](https://www.docker.com/) (required for wp-env)

**Note:** Ensure Docker is running (`docker ps`) before proceeding.

### Setup Repository and Packages

1. Clone the repository:
```bash
git clone https://github.com/wpengine/hwptoolkit.git
```

2. Install dependencies:
```bash
cd hwptoolkit && npm install
```

3. Configure environment variables:
```bash
echo "NEXT_PUBLIC_WORDPRESS_URL=http://localhost:8890" > examples/next/woocommerce/example-app/.env
```

### Build and Start the Application

1. Navigate to the example directory:
```bash
cd examples/next/woocommerce
```

2. Build and start everything:
```bash
npm run example:build
```

This command will:
- Start [wp-env](https://developer.wordpress.org/block-editor/getting-started/devenv/get-started-with-wp-env/)
- Import the database from [wp-env/db/database.sql](wp-env/db/database.sql)
- Install Next.js dependencies
- Start the development server

### Access Your Application

| Frontend | Admin |
| ------------------------------------------------ | ------------------------------------------------------------------ |
| [http://localhost:3000/](http://localhost:3000/) | [http://localhost:8890/wp-admin/](http://localhost:8890/wp-admin/) |

> **Admin Credentials:** Username: `admin` | Password: `password`

### Command Reference

| Command | Description |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `example:build` | Prepares the environment by starting WordPress, importing the database, and starting the application. |
| `example:dev` | Runs the Next.js development server. |
| `example:dev:install` | Installs the required Next.js packages. |
| `example:start` | Starts WordPress and the Next.js development server. |
| `example:stop` | Stops the WordPress environment. |
| `example:prune` | Rebuilds and restarts the application by destroying and recreating the WordPress environment. |
| `wp:start` | Starts the WordPress environment. |
| `wp:stop` | Stops the WordPress environment. |
| `wp:destroy` | Completely removes the WordPress environment. |
| `wp:db:query` | Executes a database query within the WordPress environment. |
| `wp:db:export` | Exports the WordPress database to `wp-env/db/database.sql`. |
| `wp:db:import` | Imports the WordPress database from `wp-env/db/database.sql`. |

> **Tip:** Run `npm run wp-env` for additional wp-env commands. See the [official documentation](https://www.npmjs.com/package/@wordpress/env) for more details.

### Database Access

To access the database via phpMyAdmin, add this to your wp-env configuration:
```json
"phpmyadminPort": 11111
```

Check if port 11111 is available: `lsof -i :11111`

## Manual WordPress Setup

### Prerequisites

- **Node.js** (v18+ recommended)
- **Package manager**: npm, yarn, pnpm, or bun
- **WordPress instance** with required plugins with php 8.0 due to WPGraphQL for WooCommerce

### Required WordPress Plugins

Install and activate these plugins in your WordPress admin:

1. **WPGraphQL** - Exposes WordPress data via GraphQL
2. **WPGraphQL Headless Login** - Enables authentication for headless setups
3. **WPGraphQL for WooCommerce (WooGraphQL)** - Adds WooCommerce GraphQL support

### Plugin Configuration

1. Navigate to **GraphQL** → **Settings** in your WordPress admin
2. Under **WPGraphQL Headless Login**, enable **Credentials Authentication**
3. When installing WooCommerce no extra additional plugins or add-ons are required.
4. [Optional] Go in WP Admin -> All Products -> Import and use the `sample_products.csv` from `/wp-env/` folder.


![Enable Credentials Authentication](./screenshots/enable-credentials-auth.png)

### Environment Setup

Create a `.env` file in the `example-app` directory:

```env
NEXT_PUBLIC_WORDPRESS_URL=https://your-wordpress-site.com
```

> **Important:** Use your actual WordPress URL without a trailing slash.

### Getting Started

1. **Install dependencies:**
```bash
npm install
# or yarn install / pnpm install / bun install
```

2. **Start development server:**
```bash
npm run dev
# or yarn dev / pnpm dev / bun dev
```
43 changes: 43 additions & 0 deletions examples/next/woocommerce/example-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# env files (can opt-in for committing if needed)
.env*

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts

package-lock.json
32 changes: 32 additions & 0 deletions examples/next/woocommerce/example-app/codegen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { CodegenConfig } from "@graphql-codegen/cli";
import dotenv from "dotenv";
import path from 'path';
dotenv.config({path: path.resolve(process.cwd(), '.env.local')});

const baseUrl =
process.env.NEXT_PUBLIC_WORDPRESS_URL || "https://your-wordpress-site.com";
const graphqlPath = process.env.NEXT_PUBLIC_GRAPHQL_PATH || "/graphql";
const introspectionToken = process.env.GRAPHQL_INTROSPECTION_TOKEN || "";

const config: CodegenConfig = {
schema: [
{
[`${baseUrl}${graphqlPath}`]: {
headers: {
Authorization: introspectionToken,
},
},
},
],
documents: ["src/**/*.jsx"],
generates: {
"possibleTypes.json": {
plugins: ["fragment-matcher"],
config: {
module: "commonjs",
apolloClientVersion: 3,
},
},
},
};
export default config;
21 changes: 21 additions & 0 deletions examples/next/woocommerce/example-app/components.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": false,
"tsx": false,
"tailwind": {
"config": "",
"css": "src/styles/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"generator": "Code Snippets v3.6.8",
"date_created": "2025-03-06 10:59",
"snippets": [
{
"id": 8,
"name": "disable-introspection-with-token",
"code": "use WPGraphQL\\Server\\ValidationRules\\DisableIntrospection as BaseDisableIntrospection;\n\nadd_filter('graphql_introspection_token', function () {\n return 'your-secure-introspection-token'; // PLEASE CHANGE ME!!!\n});\n\n/**\n * Class DisableIntrospectionRule\n *\n * Custom rule to disable GraphQL introspection unless a valid token is provided.\n */\nclass DisableIntrospectionRule extends BaseDisableIntrospection {\n public function __construct() {\n // Register the custom validation rule.\n add_filter('graphql_validation_rules', [$this, 'add_custom_validation_rule']);\n }\n\n /**\n * Adds the custom validation rule for disabling introspection.\n *\n * @param array $rules Existing validation rules.\n * @return array Modified validation rules.\n */\n public function add_custom_validation_rule(array $rules): array {\n $rules['disable_introspection'] = $this;\n return $rules;\n }\n\n /**\n * Determines if the introspection should be disabled.\n *\n * @return bool True if introspection should be disabled, false otherwise.\n */\n public function isEnabled(): bool {\n // Check if introspection is already allowed by parent rules\n $is_rule_enabled = parent::isEnabled();\n\n // If introspection is already allowed, there is no need for further checks\n if (!$is_rule_enabled) {\n return false;\n }\n\n // Retrieve the authorization header\n $introspection_token_header = isset($_SERVER['HTTP_AUTHORIZATION']) \n ? sanitize_text_field($_SERVER['HTTP_AUTHORIZATION']) \n : '';\n // If no token is provided, keep introspection disabled\n if (empty($introspection_token_header)) {\n return true;\n }\n\n // Retrieve the stored introspection token\n $introspection_token = apply_filters('graphql_introspection_token', '');\n\n // If no token is configured, keep introspection disabled\n if (empty($introspection_token)) {\n return true;\n }\n\n // Compare the provided token with the stored token\n return !hash_equals($introspection_token_header, $introspection_token);\n }\n}\n\n// Initialize the custom validation rule\nnew DisableIntrospectionRule();",
"active": true,
"modified": "2025-03-06 10:59:20",
"revision": "10"
}
]
}
14 changes: 14 additions & 0 deletions examples/next/woocommerce/example-app/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const compat = new FlatCompat({
baseDirectory: __dirname,
});

const eslintConfig = [...compat.extends("next/core-web-vitals")];

export default eslintConfig;
7 changes: 7 additions & 0 deletions examples/next/woocommerce/example-app/jsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}
29 changes: 29 additions & 0 deletions examples/next/woocommerce/example-app/next.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
images: {
remotePatterns: [
// Dev
{
protocol: "http",
hostname: "localhost",
port: "8890",
pathname: "/wp-content/uploads/**",
},
{
protocol: "http",
hostname: "127.0.0.1",
port: "8890",
pathname: "/wp-content/uploads/**",
},
// ✅ Production
{
protocol: "https",
hostname: "your-production-site.com",
pathname: "/wp-content/uploads/**",
},
],
},
};

export default nextConfig;
Loading
Loading