Creating a Custom Theme

TABLE OF CONTENTS

Introduction

Webstore front-end development focuses on crafting a user-friendly interface that seamlessly interacts with the back-end via APIs. This process includes designing visually appealing product pages, intuitive shopping carts, and smooth checkout experiences. By connecting with APIs, the webstore can dynamically retrieve and update data, enabling real-time content and transactions. Prioritizing user experience, mobile responsiveness, and efficient API integration is essential for successful front-end development in a Znode-powered Storefront.


Development Setup

  • The development setup included CLI installation, webstore SDK, environment variables and other configurations and also making sure  your web store application is up and running.
  • For detailed instructions on setting up the local development environment, please refer to the  Development Setup Guide
  • Please ensure the below environment variables are configured properly once the development setup  step is executed.

Environment Variables

Set the following variables in your .env file located at the root of the project. These environment variables are essential for configuring authentication, APIs, caching, security, and third-party integrations.

Authentication Section

VariableDescriptionExample
NEXTAUTH_URLBase URL for NextAuth authentication callbacks.http://localhost:3000
NEXTAUTH_SECRETSecret key for encrypting JWTs and securing cookies.

This is random key, we can define in order to internal authentication 
ABCDEF
(Its can be any value customer is preferred)


API Configuration Section

VariableDescriptionExample
API_URLBase URL for the backend API.https://backend-api.com/api
API_DOMAINDomain for accessing
the primary API. This should be api domain name in fro API_URL
api-domain-name
API_V2_DOMAINDomain for accessing version 2 of the API.api-v2-domain-name
API_KEYAPI key for authenticating requests.******


Payment Services section

VariableDescriptionExample
NEXT_PUBLIC_PAYMENT_MANAGER_URLURL for the Payment Manager service (exposed to the client).https://payment-service.com


Location Services section

VariableDescriptionExample
NEXT_PUBLIC_GEO_CODE_URLURL for geocoding services (exposed to the client).https://geo-service.com
NEXT_PUBLIC_GOOGLE_MAP_API_KEYAPI key for Google Maps services (exposed to the client).******


Logging & Caching section

VariableDescriptionExample
LOGGING_METHODMethod for logging application events (FILE or CONSOLE).File
CACHE_MEMORYCache storage type (MEMORY or FILE). client).File
ENABLE_CACHEFlag to enable or disable caching.true


Application Settings section

VariableDescriptionExample
WEBSTORE_DOMAIN_NAMEDomain name for the webstore.http://localhost:3000
DEFAULT_THEMESets the default theme for the webstore.base
STORAGESpecifies storage type used by the application. (file, redis, or cdn)file
REDIS_CONNECTION_STRINGConnection string for Redis database.redis://localhost:6379
APP_NAMEName of the application.WEBSTORE
IS_DEBUGGINGEnables or disables debugging mode.false


Security Policies

VariableDescriptionExample
CONTENT_SECURITY_POLICYDefines allowed content sources for security.default-src 'self'
NODE_TLS_REJECT_UNAUTHORIZEDDisables SSL validation (use only for local development).0


Project Setup

Open the terminal and move into the project directory using the following command:

cd <project_directory>

Replace <project_directory> with the name of the directory created during the Znode 10 CLI installation process.

Install Dependencies

Run the following command to install project dependencies:

npm install

Configure Environment Variables

In the root directory of the project, update the .env file with the following keys and corresponding values:

NEXT_PUBLIC_BaseUrl = https://localhost:44375/
NEXT_PUBLIC_PAYMENT_DOMAIN_NAME = https://localhost:44322/
NEXT_PUBLIC_REDIS_CONNECTION_STRING = "redis://localhost:6379"
NEXT_PUBLIC_API = "http://localhost:3000"
  • NEXT_PUBLIC_BaseUrl: Connects to API endpoints within the application.
  • NEXT_PUBLIC_PAYMENT_DOMAIN_NAME: Specifies the payment domain name for various payment options.
  • NEXT_PUBLIC_REDIS_CONNECTION_STRING: Redis connection string for caching mechanisms.
  • NEXT_PUBLIC_API: Connects to the Next application Backend-for-Frontend (BFF) layer. The default value is http://localhost:3000, suitable for local development.

Content Security Policy Headers

All Content Security Policy (CSP) header values should be configured correctly in the following key:

CONTENT_SECURITY_POLICY

Access the Local Webstore

Execute the following command to run the project:

PS D:\project-directory> npm run dev

Open a web browser and go to the specified localhost address, usually http://localhost:3000.

Note: Ensure that there is an entry in the Znode domain database table for seamless integration.

Znode Webstore Application

Folder Structure

  • .husky:
    Configuration for Git hooks; enforces code quality checks and other tasks before committing.
  • .next:
    Auto-generated folder during Next.js build; contains compiled assets, server-side code, and build artifacts.
  • .vscode:
    Configuration for Visual Studio Code; includes editor settings specific to the project.
  • app/[lang]:
    Dynamic folder based on the language name.
    • themes/[themeName]:
      Routes for themes are managed here. If no files are found, the base theme is used.
  • api:
    Backend-for-Frontend (BFF) API routes; aggregates Znode APIs into a single endpoint.
  • global-error.tsx:
    React component for handling global errors.
  • client-services / client-helper:
    Helpers to interact with the browser.
  • client-api.ts / client-payment-api.ts:
    Used to establish a connection to the BFF layer.
  • components
    • Client Components
      • Render content on the client side.
      • Interactive and dynamic user interfaces.
      • Marked with “use client”.
    • Server Components
      • Perform server-side operations.
      • Used for server-side rendering and data fetching.
  • components/themes:
    Organizes theme-specific components. Falls back to base theme if components are missing.
  • components/errors:
    Manages content retrieval failures, server errors, 404s, and unpublished stores.
  • middleware
    • APIAuthMiddleware: Handles Account API authentication.
    • PortalMiddleware: Manages portal-specific middleware tasks.
  • patches:
    Bug fixes and overrides for third-party libraries.
  • constants:
    Central repository for static values.
  • context:
    Manages React context providers for state sharing.
  • i18n:
    Configuration for internationalization.
  • messages:
    Contains localization files.
  • scripts:
    Build and deployment scripts.
  • types:
    Contains interfaces to promote type safety.
  • public:
    Hosts static assets like images and fonts.
  • services:
    Contains API calls to the Znode API.

File Structure

  • Configuration Files:
    .dockerignore, .env, .eslintrc.json, .gitignore, .prettierrc, tsconfig.json, etc.
  • Redis Cache Handler:
    cache-handler-redis.js handles caching logic using Redis.
  • Linting:
    commitlint.config.ts for consistent commit messages.
  • Docker/Kubernetes:
    docker-compose.yml, Dockerfile, and kubernetes-Automation-deploy.yml for deployment.
  • Internationalization:
    i18n.ts, next-i18next.config.js.
  • Middleware:
    middleware.ts defines custom middleware.
  • Theme Configuration:
    theme.config.js manages theme settings.

How to Update the Theme

When updating a theme, modifications may include styling changes, data display adjustments, or enhanced functionality. Use the following steps and paths based on the requirement.

Steps to Update the Theme

  1. Creating or Updating Routes
    • Path: app/[lng]/themes/B2B or app/[lng]/themes/bstore
    • Action: Modify or add routes in the theme directory.
  2. Modifying Components
    • Path: components/themes/B2B/Components
    • Action: Update or override components. Use the same component name for overrides to be effective.
  3. Updating APIs
    • Path: api/your-route
    • Action: Create or modify APIs relevant to components and account sections.
  4. Handling Errors
    • Path: components/errors
    • Action: Update components to manage errors appropriately.
  5. Managing Language Files
    • Path: messages
    • Action: Modify localization JSON files (e.g., base-DE.json).
  6. Customizing Services
    • Path: services/agents/AccountAgent.ts
    • Action: Modify service agents as needed.
  7. Updating Constants
    • Path: constants/index.ts
    • Action: Adjust global constants used throughout the theme.
  8. Context and State Management
    • Path: context
    • Action: Modify context providers and hooks.
  9. Type Definitions
    • Path: types, client-service-types/VouchersTypes.ts
    • Action: Update interfaces and types for consistency.

Note: Component names must match existing B2B theme components for effective overrides. Server-side rendering is preferred unless client components are necessary for the account section. Keep modifications consistent and well-documented.


Creating a New Theme

Creating a new theme involves configuration, folder creation, and environment setup.

Step One – Update theme.config.js

Add a new theme object based on the “B2B” theme:

module.exports = {
  B2B: {
    base: "B2B",
    extended: "B2B",
    name: "B2B"
  },
  themeName: {
    base: "B2B",
    extended: "{yourThemeName}",
    name: "{Your Theme Name}"
  }
};

Step Two – Update .env File

Set the new theme as the default:

DEFAULT_THEME = {yourThemeName}

Step Three – Create Theme Folders

Create the following folders:

  • app/[lng]/themes/{yourThemeName}
  • components/themes/{yourThemeName}

Step Four – Associate Theme to a Store

In the Admin Console, assign the new theme to an existing store and save the configuration.

Step Five – Deploy the Theme

Run the development build:

npm run dev {themeName}

This will create new folders:

  • app/[lng]/themes/B2B_{yourThemeName}
  • components/themes/B2B_{yourThemeName}

These contain component copies from the B2B theme for overrides.

Creating and Updating Components

Before creating a new component, decide on the theme to use or customize.

Path:

components/themes/{yourThemeName}/components

Create Your Component

Create a file in the theme’s component folder:

components/themes/{yourThemeName}/components/YourComponent.tsx

Decide Server or Client Component

  • Server Component
    Data is fetched server-side and not exposed to the browser.
  • Client Component
    Similar to standard React components; uses hooks and manages data on the client side.

Note: Prefix client components with "use client" to enable client-side rendering.

Implementing Hooks (Client Components)

Follow Next.js documentation for client components. Example:

// components/themes/yourtheme/components/YourComponent.tsx
"use client";
const YourComponent = () => {
  const { data, loading, error } = useData(); // Replace with actual hook
  if (loading) {
    return <p>Loading...</p>;
  }
  if (error) {
    return <p>Error: {error.message}</p>;
  }
  return (
    <div>
      <h2>Your Component</h2>
      <p>{data}</p>
    </div>
  );
};

export default YourComponent;

Note: It is recommended to create components in a new theme.

Creating a New Page

Navigate to:

app/[lang]/themes/{yourThemeName}

Customize the theme files to match branding and design.

Creating Pages

  • Dynamic Page
    Example for a blog detail page:

components/themes/yourtheme/blog/[blogId]/page.tsx
const BlogDetailPage = async ({ params: { blogId } }: { params: { blogId: number } }) => {
  return <div>Blogging Page</div>;
};

export default BlogDetailPage;


Static Page
Example for a static blog page:

components/themes/{yourThemeName}/blog/myblog/page.tsx


const BlogDetailPage = async () => {
  return <div>Blogging Page</div>;
};
export default BlogDetailPage;


Deploying a React Theme

Development Build

Run the following command:

npm run dev {themeName}


This starts the build at http://localhost:3000 and generates:

  • app/[lng]/themes/B2B_{yourThemeName}
  • components/themes/B2B_{yourThemeName}

These folders hold component overrides for the new theme.

Production Build

Run the following command:

npm run build

This generates the production build in the .next folder.

Theme Paths - Where to Manage Theme Items

  • Creating Routes
    app/[lng]/themes/{yourThemeName}
  • Creating Components
    components/themes/{yourThemeName}/Components
  • Creating APIs
    api/your-route
  • Handling Errors
    components/errors
  • Managing Language Files
    messages
  • Customizing Services
    services/agents/AccountAgent.ts
  • Updating Constants
    constants/index.ts
  • Context and State Management
    context
  • Type Definitions
    types, client-service-types/VouchersTypes.ts

Did you find it helpful? Yes No

Send feedback
Sorry we couldn't be helpful. Help us improve this article with your feedback.