Geek Culture

A new tech publication by Start it up (https://medium.com/swlh).

Follow publication

Headless WooCommerce & Next.js: Set up Next.js

Leo Chan
Geek Culture
Published in
5 min readJul 30, 2021

--

Photo by Denys Nevozhai on Unsplash

I’ve chosen to use Next.js for this project namely because it is a static-site generator that also makes it easy to handle back-end functionality.

By default, Next.js pre-renders every page to generate HTML in advance, resulting in better performance and SEO. Next.js recommends using Static Generation when pre-rendering so the HTML is generated at build time and will be reused on each request.

When fetching data, we can use getStaticProps which fetches data at build time and can improve performance if the data is available ahead of a user’s request. My products are available at build time but what if I change any details later? The clever thing with getStaticProps is it isn’t totally static — there is a revalidate feature which allows for page re-generation after a pre-defined amount of time. The regeneration happens in the background and once available the new page with the new data will be served up instead.

Set up your Next.js project

I’ve chosen to use TypeScript when creating my Next.js project but you can choose what you like. I’m also using yarn but you could equally use npm.

yarn create next-app woocommerce-nextjs --typescriptnpx create-next-app woocommerce-nextjs --ts

I’ve recently learnt TypeScript and am trying to use it in my projects to build up familiarity with it. There is a good YouTube video by Academind that gives a great overview from a beginner’s perspective. TypeScript helps you avoid most runtime errors at the time you are developing your code and this is particularly useful if you are working with a team so other developers can explicitly understand what Types they need to work with and rely on their IDE to flag up errors as they arise.

Once set up, you can run yarn dev or npm run start to start your local dev server and see your website at localhost:3000. You’ll see the default Next.js welcome screen.

Screenshot of default Next.js welcome screen

Fetch products from WooCommerce

We could and maybe should design some of the front-end components with dummy data which we can then replace with dynamic data. However, I’m diving straight into fetching the data so you can see how it’s done and can then go wild with your own front-end design before you implement data fetching for yourself.

Create a fetch function

In the previous article, I pointed out the WooCommerce REST API authentication differed for HTTP (OAuth 1.0a) and HTTPS (Bearer Auth). We are using HTTP with the local Wordpress site so we will need OAuth 1.0a authentication.

Initially, I used the oauth-1.0a,crypto and axios libraries to make API calls but WooCommerce has an official JavaScript library so I wanted to try using this instead.

yarn add @woocommerce/woocommerce-rest-api --devnpm install --save @woocommerce/woocommerce-rest-api

The package doesn’t come with its own type definitions — you can get community created types from the DefinitelyTyped resource.

yarn add @types/woocommerce__woocommerce-rest-api --devnpm install --save @types/woocommerce__woocommerce-rest-api

The first thing we need to do is create a function to fetch our products from WooCommerce. I created a utils folder in the root structure and created a file in there wooCommerceApi.ts to hold my functions.

You’ll see that we need to initialise WooCommerceRestApi with key credentials. If you remember, you already have the consumer key and secret from the WooCommerce settings. I want to keep the key and secret private and away from prying eyes so I use environment variables.

Note: With Next.js environment variables are only available server-side unless you add a prefix of NEXT_PUBLIC_. Adding NEXT_PUBLIC_ (e.g. NEXT_PUBLIC_WOOCOMMERCE_KEY) would expose this environment variable to the browser so you can use it client-side. However, environment variables exposed to the browser can still be retrieved by someone who knows how so secrets are best left to the server-side where the environment is more secure.

Note: In the gist above, I use the exclamation mark on the end of the environment variables simply to resolve a typescript error concerning the possibility of a null value when a string must be passed. The exclamation mark indicates there will definitely be a value.

Fetch the products

Now that we have a function to fetch the products we need to use it! For this example, we can use the index.tsx page and we simply want to see a console log of the products for now.

I mentioned getStaticProps in the introduction and that is exactly what we’re going to use. We do the data fetch within the getStaticProps function (unique to Next.js) so that the fetch happens at build time and the result is a faster website because it is pre-rendered.

Take a look at the Next.js developer docs to find out more about how it handles data fetching. I won’t dive into it but you’ll see in the gist below that the response for our data fetch is returned as an object and this becomes available in the props for the functional component itself.

Everything within return () is simply the boilerplate code that comes with Next.js and is the welcome screen. None of it is necessary right now. We’re interested in getStaticProps.

If you are using regular JavaScript rather than TypeScript then you should be able to see a console log of the products you added in WooCommerce.

Those following my tutorial will notice I have declared the type interface for Props and passed a custom type definition of Product in there. You could pass any[] and that would work fine but I thought I’d try and do it properly and I found a type definition for the WooCommerce product object in this GitHub repo by rrrhys which I used and updated slightly by cross-referencing with the WooCommerce developer docs.

I included it in a wooCommerceTypes.ts file that I created in the utils folder. It’s all in the gist below but it’s very long and potentially frightening.

Not all of it is relevant right now but most of the useful types are there so it’s all going in. If you take your time to comb through each interface you’ll see they are simply describing the objects and what we can expect (e.g. billing address, order).

Let’s leave the article here so there is nothing else important after this long gist.

--

--

Leo Chan
Leo Chan

Written by Leo Chan

Lockdown coder: transformation from non-coder to coder in under 12 months…complete-ish.

Responses (2)

Write a response