-
Notifications
You must be signed in to change notification settings - Fork 2
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
alexwpengine
wants to merge
24
commits into
main
Choose a base branch
from
example-next-woocommerce
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
678ac3c
WIP
alexwpengine 862398e
Merge branch 'main' into example-next-woocommerce
alexwpengine 09d1302
WIP
alexwpengine a8fdc1a
WIP
alexwpengine 76cb863
WIP
alexwpengine 1085b7c
WIP
alexwpengine aaa7735
progress
alexwpengine 2f2e328
auth finalized
alexwpengine 501751a
new update
alexwpengine d921e4b
cart rdy
alexwpengine 7e11ae1
product and templates and optimizations
alexwpengine bf2a884
my account rdy
alexwpengine dc8bd39
Checkout ongoing
alexwpengine 0cc1223
variations
alexwpengine d68f792
optimizing it as TypeScript
alexwpengine df09a79
checkout for guest and order received
alexwpengine f6d4694
order received rdy
alexwpengine a1e7f8c
grouped products, clear up code, update db
alexwpengine 36082d1
update .env desc
alexwpengine b620ae6
Update examples/next/woocommerce/example-app/src/components/OrderRece…
alexwpengine eadea27
Update examples/next/woocommerce/example-app/src/components/Products/…
alexwpengine e4d71cc
improvements
alexwpengine bc55833
remove console logs
alexwpengine c85a016
Update examples/next/woocommerce/example-app/src/components/Products/…
alexwpengine File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | ||
|
|
||
|
|
||
|  | ||
|
|
||
| ### 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| } |
14 changes: 14 additions & 0 deletions
14
examples/next/woocommerce/example-app/disable-introspection-with-token.code-snippets.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| } | ||
| ] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| { | ||
| "compilerOptions": { | ||
| "jsx": "react", | ||
| "paths": { | ||
| "@/*": ["./src/*"] | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.