Skip to main content

@ensono-stacks/next

The next plugin contains generators to augment existing NextJs projects. Adding eslint rules, testing config as well as installing and configuring NextAuth.js in your NextJs app.

Using a standard setup for your Next app ensures consistency and code quality across multiple applications quickly. NextAuth (alongside Redis) can also be quickly added to a project without costly configuration and setup.

Using the deployment generator you can setup your application with the necessary infrastructure config to host it in k8s.

Prerequisites

An existing Next application. Note the generator will fail if run in an empty workspace with no applications. To create a new Next application please run the NX Next generator with the following command including any relevant options. See @nx/next plugin docs

nx g @nx/next:app my-new-app

Ensure the stacks -> executedGenerators fields are present within nx.json for FE code generation.

Ensure the stacks -> config fields are present and populated within nx.json for deployment/infra generation.

An example of the expected structure can be seen here under @ensono-stacks/workspace:init​ prerequisites.

Setting up @ensono-stacks/next

Install the @ensono-stacks/next with the following command:

npm install --save-dev @ensono-stacks/next@latest

Executors and Generators

To see a list of the plugin capabilities run the following command:

nx list @ensono-stacks/next

View additional information about a plugin capability through the following command:

nx g @ensono-stacks/next:[generator-executor-name] --help

Generators

@ensono-stacks/next:init

Adds custom config and developer tools to an existing next application

The next init generator will add a custom ESlint config to an existing NextJs application, install eslint-plugin-testing-library to the project. as well as update project.json with a custom test config to allow coverage collection from jest.

Prerequisites

An existing Next application

Usage

nx g @ensono-stacks/next:init

Command line arguments

The following command line arguments are available:

OptionDescriptionTypeAccepted ValuesDefault
--projectName of the existing next applicationstringnameOfApplicationN/A

Generator Output

The following files will be updated.

UPDATE apps/baseline-next-app/project.json #Updated with custom test config to allow for coverage collection
UPDATE apps/baseline-next-app/.eslintrc.json #Ehanced with additional linting rules
UPDATE apps/baseline-next-app/tsconfig.json #Minor enhancements
UPDATE apps/baseline-next-app/tsconfig.spec.json #Updates for monorepo structure
UPDATE apps/baseline-next-app/specs/index.spec.tsx #Formatting changes

The generator will also add react-axe (version 4.7.3) into the app via the following:

...app.tsx
// @ts-ignore
if (typeof window !== 'undefined' && process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line global-require
const axe = require('@axe-core/react'); // eslint-disable-line @typescript-eslint/no-var-requires
// eslint-disable-next-line global-require
const React = require('react'); // eslint-disable-line @typescript-eslint/no-var-requires
// eslint-disable-next-line global-require
const ReactDOM = require('react-dom'); // eslint-disable-line @typescript-eslint/no-var-requires
// eslint-disable-next-line @typescript-eslint/no-floating-promises
axe(React, ReactDOM, 1000);
}

...

react-axe has been added so your app can be tested for accessibility and results will show in the Chrome DevTools console.

A final message is provided if the developer would like to run the relevant deployment generator that supports this FE. @ensono-stacks/next:init-deployment.

@ensono-stacks/next:init-deployment

Configure Deployment & Infra for your Next project

The deployment generator will provide all the necessary tools and setup ready to host your application in a Kubernetes Cluster.

Prerequisites

An existing Next application. This may already exist if you agreed to install the infra during next:init generator.

Usage

nx g @ensono-stacks/next:init-deployment

Command line arguments

The following command line arguments are available:

OptionDescriptionTypeAccepted ValuesDefault
--projectThe name of the projectnameOfApplicationstringN/A

Generator Output

├── workspace root
├── apps
├── myapp
├── deploy
├── helm
├── terraform
├── Dockerfile
├── libs
├── next-helm-chart
  • Creates numerous files; main helm config as a library next-helm-chart under libs and terraform config under the deploy folder within the app. You can then go in and update relevant parts for your use case.

  • Adds following files to .gitignore

'**/.terraform/*',
'*.tfstate',
'*.tfstate.*',
'crash.log',
'crash.*.log',
'override.tf',
'override.tf.json',
'*_override.tf',
'*_override.tf.json',
'.terraformrc',
'terraform.rc',
  • installs following dev dependencies
@nx-tools/nx-container
@nx-tools/container-metadata
@jscutlery/semver

Understanding the Infrastructure

Azure devops configuration exists within the build folder for each new generated app project. This folder lives at root.

build/azDevOps

azuredevops-runner.yaml

Here you will find the actions for triggering the pipelines. Basically, creating a PR will build as a non prod artefact and merging into main branch will build as a prod artefact, with the relevant parameter specified.

azuredevops-stages.yaml

This is of course the actual stages of the pipeline that are configured. Most of the detail is done via taskctl, which can found as the last task in the build job.

taskctl

taskctl has been used to enable across different environments and builds. Cross platform, one single syntax.

As a rule of thumb, each task here references a target execution via Nx defined inside project.json. The flag --target is used to pass in the appropriate value.

build/taskctl/tasks.yaml

helm:
description: Lint Helm Charts
command:
- npx nx affected --base="$BASE_SHA" --target=lint

apps/myapp/project.json

"lint":
{
"executor": "nx:run-commands",
"options":
{
"commands": [{ "command": "helm lint", "forwardAllArgs": false }],
"cwd": "libs/next-helm-chart/build/helm",
},
}

Helm

The configuration files for Helm Charts live inside the libs folder under directory for your app, contained as its own library

myproject/apps/myapp/libs/next-helm-chart/build/helm

As a rule of thumb, target execution is defined via Nx inside project.json. The flag --target is used to pass in the appropriate values for each intended target run.

libs/next-helm-chart/project.json

Hence, running the following will trigger the intended execution. The pipeline takes care of this for us.

npx nx affected --base="$BASE_SHA" --target=lint

In the infra pipeline, the steps for Helm will begin by linting, followed by either an upgrade or install. If the Helm chart is already installed, then an upgrade occurs based on the given command. If it isn't installed, then an installation occurs instead. The command accepts a --atomic flag which will allow Helm to roll back to the previous release should a failure during upgrade occur. On install, this would cause the installation to fail if there were any issues.

The remaining tasks are then carried out post versioning, covered in the next section.

Versioning

jscutlery:semver is an Nx plugin which has been configured to automate semantic versioning and release in these projects. It follow conventional commits and is also applied to proceeding pipeline targets such as Helm charts.

Package & Push

After versioning, our build is containerised using Docker and pushed to the set Azure registry.

Likewise, the Helm Charts are also packaged and pushed to their respective place in the Azure registry.

Finally a Github release is tagged with relevant notes using jscutlery.

Terraform

This is the last group of tasks to run as part of the infrastructure. See myproject/apps/myapp/deploy/terraform for configuration files.

One thing to highlight is that once the Terraform apply task is completed, a Helm install will also be executed. As mentioned earlier, the default behaviour is to deploy a non-production instance when a PR is created and once the PR is merged, then the deployment is made to production.

@ensono-stacks/next:next-auth

Add Next Authentication to your next application

The next-auth generator will install and configure NextAuth.js into an existing Next application. It will add the initial configuration, add the session provider, setup an API endpoint and add local environmental variables. It will also configure provider specific setup.

Prerequisites

An existing Next application

Usage

nx g @ensono-stacks/next:next-auth

Command line arguments

The following command line arguments are available:

OptionDescriptionTypeAccepted ValuesDefault
--projectThe name of the projectnameOfApplicationstringN/A
--providerThe provider to be installedstringnone/azureAdnone
--skipPackageJsonDo not add dependencies to package.jsonbooleantrue/falsefalse

Generator Output

  • Creates a new Next API endpoint with the file name [...nextauth].ts. This contains the dynamic route handler for NextAuth.js which will also contain all of your global NextAuth.js configurations. If you have specified a provider when running the generator this will be added to the providers array
/apps/appName/pages/api/[...nextauth].ts
import NextAuth from 'next-auth';
import AzureADProvider from 'next-auth/providers/azure-ad';
const nextAuth = NextAuth({
providers: [
AzureADProvider({
clientId: process.env.AZURE_AD_CLIENT_ID,
clientSecret: process.env.AZURE_AD_CLIENT_SECRET,
tenantId: process.env.AZURE_AD_TENANT_ID,
}),
],
});
export default nextAuth;
  • Install the next-auth package and add to package.json, unless the --skipPackageJson option was used
/package.json
"dependencies": {
...otherDependencies
"next-auth": "4.18.8",
},
  • Create or append an .env.local file. Adding required next auth environmental variables. These will vary depending on the provider chosen.
/.env.local
NEXTAUTH_URL=http://localhost:4200
NEXTAUTH_SECRET=secretValue
AZURE_AD_CLIENT_ID=
AZURE_AD_CLIENT_SECRET=
AZURE_AD_TENANT_ID=
note

Be sure to update the environmental variables with the values provided by your provider

/apps/appName/_app.tsx
import { AppProps } from 'next/app';
import Head from 'next/head';
import './styles.css';
import { SessionProvider } from 'next-auth/react';
function CustomApp({
Component,
pageProps: { session, ...pageProps },
}: AppProps) {
return (
<SessionProvider session={session}>
<Head>
<title>Welcome to testing!</title>
</Head>
<main className="app">
<Component {...pageProps} />
</main>
</SessionProvider>
);
}
export default CustomApp;

From here with the configuration complete it is now possible to access the useSession hook from next auth. For further information please see the Getting Started Guide to Next Auth

@ensono-stacks/next:storybook

Add Storybook to your next application

The storybook generator will install and configure Storybook into an existing Next application. It will add storybook configuration, a custom component command and storybook extensions. The following extensions are:

        {
"@storybook/addon-essentials": "7.4.5",
"@storybook/addon-actions": "7.4.5",
"@storybook/addon-links": "7.4.5",
"@storybook/manager-api": "7.4.5",
"@storybook/preview-api": "7.4.5",
"@storybook/addon-a11y": "7.4.5",
"@storybook/addon-jest": "7.4.5",
"@storybook/theming": "7.4.5",
},

Prerequisites

An existing Next application

Usage

nx g @ensono-stacks/next:storybook

Command line arguments

The following command line arguments are available:

OptionDescriptionTypeAccepted ValuesDefault
--projectThe name of the projectnameOfApplicationstringN/A
--skipPackageJsonDo not add dependencies to package.jsonbooleantrue/falsefalse

Generator Output

The generator creates the following:

  • creates a new folder .storybook. This contains information for the storybook package.
    • main.js file is created
    • preview.js file is created
  • creates a new file tsconfig.storybook.json to store configuration for storybook

The generator updates the following:

  • updates the project.json file to add the custom-component command

The generator installs the follow dependencies unless the --skipPackageJson option was used:

/package.json
{
"dependencies": {
"@storybook/core-server": "7.4.5",
},
"devDependencies": {
"@nx/storybook": "16.9.1",
"@storybook/nextjs": "7.4.5",
"@storybook/addon-essentials": "7.4.5",
"@storybook/addon-actions": "7.4.5",
"@storybook/addon-links": "7.4.5",
"@storybook/manager-api": "7.4.5",
"@storybook/preview-api": "7.4.5",
"@storybook/addon-a11y": "7.4.5",
"@storybook/addon-jest": "7.4.5",
"@storybook/theming": "7.4.5",
"eslint-plugin-storybook": "0.6.15",
},
}

Custom command for app

After the Storybook generator has been installed you can now run the new command custom-component that will add the following:

  • creates a component under a specified name
  • creates a test for the new component
  • creates a story for the new component
note

my-app is an example of your app's name.

nx run my-app:custom-component --name=component-x --folderPath=components

The flags are the following:

  • name: name of the component
  • folderPath: path of the new component folder (based on the app as the root of the path)