Build book store with next.js

We’re going to cover, step-by-step, how to use all of the major features of next.js to quickly and easily build your own app. I’m going to use it in combination with Tailiwind CSS.
The sample app consist of: book store overview page, book detail and cart pages. Functional parts: add a book to the shopping cart, change quantity of book (book details/shopping cart), remove the book from the shopping cart.
You can find source code of the sample here.
Step 1. Install
To create a new next.js with Tailiwind CSS (CSS framework) we will use most common approach Create Next App:
npx create-next-app -e with-tailwindcss my-project
cd my-project
Step 2. Project structure
Once project have been created, we can set up project structure in my case it looks like this in the end:
book-store-nextjs
├── ...
└── components
└── pages
└── api
└── data
└── utils
data
folder contains provider class to work with JSON data and the data file itself.
utils
folder has only single helper to work with API.
components
folder contains components for the pages.
Step 3. Routing
Page without parameters: /books
To add page you need to create a file inside pages
folder with export default component (page component) inside. So, the name of the file will be the route path. Also you can create a folder and add index.js
with component inside then the name of the folder will be your path to the page.
Page with parameter: /books/{id}
In case you need pass a parameter to your page like id
then you need name your file as a parameter in brackets. Let's say you want to open book details by route books/{id}
then you need to add [id].js
in books folder.
Page with multiple parameters /books/{genre}/{id}
When you need to add multiple parameters than name you file like this [...params].js
that way you'll catch all paths to the books route if you place it in books folder.
The same rules applies to API routes inside api
folder.
Step 4. Data Fetching
Incremental Static Regeneration
getStaticProps
is executed server side during build time. You can write server-side code directly in here. This includes fetch external data, reading from the filesystem or a database etc.
getStaticPaths
set up paths to pre-render in build time in case you’re using dynamic routing (routes with parameters) in combination with getStaticProps
Server-side Rendering
getServerSideProps
is executed server side per each request. You can write server-side code directly in here as well.
Summary
Next.js is nice tool with great documentation and quite straightforward in usage.
It’s good for e-commerce and apps where we need them to be indexed by search engines.
One more word about Tailwind CSS, it makes life much more easier when it comes to working with CSS.