Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
678ac3c
WIP
alexwpengine Aug 5, 2025
862398e
Merge branch 'main' into example-next-woocommerce
alexwpengine Aug 5, 2025
09d1302
WIP
alexwpengine Aug 13, 2025
a8fdc1a
WIP
alexwpengine Aug 29, 2025
76cb863
WIP
alexwpengine Sep 4, 2025
1085b7c
WIP
alexwpengine Sep 5, 2025
aaa7735
progress
alexwpengine Oct 27, 2025
2f2e328
auth finalized
alexwpengine Oct 28, 2025
501751a
new update
alexwpengine Oct 28, 2025
d921e4b
cart rdy
alexwpengine Oct 30, 2025
7e11ae1
product and templates and optimizations
alexwpengine Oct 31, 2025
bf2a884
my account rdy
alexwpengine Nov 3, 2025
dc8bd39
Checkout ongoing
alexwpengine Nov 4, 2025
0cc1223
variations
alexwpengine Nov 7, 2025
d68f792
optimizing it as TypeScript
alexwpengine Nov 10, 2025
df09a79
checkout for guest and order received
alexwpengine Nov 10, 2025
f6d4694
order received rdy
alexwpengine Nov 13, 2025
a1e7f8c
grouped products, clear up code, update db
alexwpengine Nov 28, 2025
36082d1
update .env desc
alexwpengine Nov 28, 2025
b620ae6
Update examples/next/woocommerce/example-app/src/components/OrderRece…
alexwpengine Dec 3, 2025
eadea27
Update examples/next/woocommerce/example-app/src/components/Products/…
alexwpengine Dec 3, 2025
e4d71cc
improvements
alexwpengine Dec 3, 2025
bc55833
remove console logs
alexwpengine Dec 3, 2025
c85a016
Update examples/next/woocommerce/example-app/src/components/Products/…
alexwpengine Dec 4, 2025
9b55c15
minor fixes
ahuseyn Jan 12, 2026
a8eb5eb
update uploads.zip
alexwpengine Jan 12, 2026
4751206
Merge branch 'main' into example-next-woocommerce
ahuseyn Jan 12, 2026
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

## 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
4. **WooCommerce**

### 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=http://localhost:8890
NEXT_PUBLIC_GRAPHQL_PATH=/graphql
SESSION_TOKEN_LS_KEY=woocommerce_session_token
REFRESH_TOKEN_LS_KEY=my_refresh_token
AUTH_TOKEN_LS_KEY=my_auth_token
AUTH_KEY_TIMEOUT=30000
```

> **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
```
### Notes
1. Single order (thank you page) can be accessed via http://localhost:3000/order-received/193?key=wc_order_UENFOwBPGaDlx. It's based on the wc_key instead of order id.
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;
8 changes: 8 additions & 0 deletions examples/next/woocommerce/example-app/jsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"compilerOptions": {
"jsx": "react",
"paths": {
"@/*": ["./src/*"]
}
}
}
Loading