Tag: NextJS

Dependency Injection with NextJS and TypeScript

Coming from a backend world, one thing that stands out when you start writing code in JavaScript, be it React, NextJS, Vue etc, is there's no great focus on code structure. Things like TypeScript bring back the concept of type checking that you'd be used to with a compiled language, and NextJS will give anyone familiar with ASP.NET MVC an alternative pattern for how a website should be constructed. But you can get the whole way through the NextJS tutorial without concepts like single responsibility, inversion of control or CQRS being mentioned once.

Now if your building a small site, maybe you can get away with not knowing or imlementing these things, but if you want to make code that's scalable or maintainable, it doesn't matter if you write in JavaScript or C# the same issues will exist but fortunately the same solutions do too.

Code Smells

Lets take a look at one of the functions on this site which gets the latest blog posts on the homepage.

import gql from 'graphql-tag';
import { Client, ApolClient } from '../prismicHelpers'

// Models
import { FeaturedPost } from "../../Models/FeaturedPost"

const latestPostsQuery = gql`
query latestPosts($category: String) {
allPosts (where : {category: $category}, first : 10, sortBy: post_date_DESC){
  edges {
    node {
      category {
        ... on Categories {
          name
        }          
      },
      title,
      image,
      post_date
      _meta {
        uid
      }
    }
  }
}
}
`;

export const getLatestPosts = async (category?: String) : Promise<FeaturedPost[]> => {
const queryOptions = {
  query: latestPostsQuery,
  variables: { category },
};

return new Promise((resolve, reject) => { ApolClient.query(queryOptions).then(response => {
  var posts: Array<FeaturedPost> = [];
  response.data.allPosts.edges.map((edge: { node: { title: { text: any; }[]; category: any; image: any; post_date: Date; _meta: { uid: any; }; }; }, key: any) => {
    posts.push({
      type: "post",
      title: edge.node.title[0].text,
      image: edge.node.image,
      uid: edge.node._meta.uid,
      category: edge.node.category?.name,
      postDate: edge.node.post_date
    })
  })
  resolve( posts);
}).catch(error => {
  reject(error);
});
});
};

This bit of code queries Prismic's GraphQL API to get the latest 10 articles for a category and then maps the result onto an internal FeaturedPost model.

Some good things about it:

  • The Prismic logic is abstracted away from the rest of the application by mapping the results to a model.
  • It follows single responsibility by doing just 1 job.
  • All config for the API (e.g. URI) are separated into a common function rather than being duplicated.

However even though I've seen countless JavaScript examples which don't even do these good things, if this were C# and I was reviewing a pull request, I'd say it smelt and needed changing.

Here's some bad things about it:

  • It's taking a dependency on Apollo Client, which while is a great client for doing GraphQL queries, at the rate JS frameworks come and go we can't say we'll never replace it and in a large application that has countless queries that would be a lot of code to update.
  • There's also no way anything can call this without also taking a dependency on it. That means I now have a hierarchy of at least 3 functions with each one dependent on the next. If I ever wanted to add unit tests to my project I'd have a big problem.

Dependency Injection using TSyringe

These issues can be solved using Dependency Injection. There's quite a few around but the one I've chosen is TSyringe (https://github.com/microsoft/tsyringe).

It's built by Microsoft, which gives me some confidence in the amount of QA that will have gone into it, but more importantly it works the way I expect a DI framework to work. There's a good chance this could be because I'm used to working in the Microsoft stack and it therefore has natural similarities to DI frameworks in their own languages.

How to add TSyringe to a NextJS project

There's nothing specifically NextJS about TSyringe, you could use it with any TypeScript/JavaScript project, it just happens that that's what my blog is built using. However it also had a few issues getting it to work and I couldn't any articles around which explained how.

To set it up...

First install the package tsyring and reflect-metadata using npm.

npm install --save tsyringe reflect-metadata

Modify your tsconfig.json file to include the following settings, which will allow the use of decorators in TypeScript.

{
"compilerOptions": {
  "experimentalDecorators": true,
  "emitDecoratorMetadata": true
}
}

Now there's a few more packages your going to need. As of NextJS 12, Babel is no longer used and has been replaced with SWC to provide faster compile times. However TSyringe and most other DI frameworks use decorators to function (hence the tsconfig.js setting to turn them on), but the setting for SWC to allow this set to false in NextJS and there's no way for you to provide your own config. Fortunately Babel is still supported and you can customise it. Hopefully a future version of NextJS will address this.

Install the following packages as dependencies.

npm install -D @babel/core @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators babel-plugin-transform-typescript-metadata

Add a .bablerc file to your project with the following settings.

{
"presets": ["next/babel"],
"plugins": [
  "babel-plugin-transform-typescript-metadata",
  ["@babel/plugin-proposal-decorators", { "legacy": true }],
  ["@babel/plugin-proposal-class-properties", { "loose": true }]
]
}

Finally add this import to your _app.tsx file.

import "reflect-metadata";

Using TSyringe

We're now ready to convert the code I had before into something more maintainable.

First I'm going to create a GraphQL Client interface which all my queries will use when they want to call a graph API. This has one function called query, which my functions will pass the graph syntax too along with a variables object.

import { DocumentNode } from "graphql";

export interface graphClient {
query(query: DocumentNode, variables?: {}): any;
}

With this interface I can now turn my getLatestPosts function into a class with a constructor that will take in the instance of graphClient.

import { inject, injectable } from "tsyringe";
import { iGetLatestPosts } from "./iGetLatestPosts";
import gql from "graphql-tag";
import { graphClient } from "../iGraphQl";

// Models
import { FeaturedPost } from "../../Models/FeaturedPost";

@injectable()
export class getLatestPosts implements iGetLatestPosts {
graphClient: graphClient;

constructor(@inject("graphClient") private graphClientParam: graphClient) {
  this.graphClient = graphClientParam;
}

private latestPostsQuery = gql`
  query latestPosts($category: String) {
    allPosts(
      where: { category: $category }
      first: 10
      sortBy: post_date_DESC
    ) {
      edges {
        node {
          category {
            ... on Categories {
              name
            }
          }
          title
          image
          post_date
          _meta {
            uid
          }
        }
      }
    }
  }
`;

public getLatestPosts = async (
  category?: String
): Promise<FeaturedPost[]> => {
  return new Promise((resolve, reject) => {
    this.graphClient
      .query(this.latestPostsQuery, { category })
      .then((response: any) => {
        var posts: Array<FeaturedPost> = [];
        response.data.allPosts.edges.map(
          (
            edge: {
              node: {
                title: { text: any }[];
                category: any;
                image: any;
                post_date: Date;
                _meta: { uid: any };
              };
            },
            key: any
          ) => {
            posts.push({
              type: "post",
              title: edge.node.title[0].text,
              image: edge.node.image,
              uid: edge.node._meta.uid,
              category: edge.node.category?.name,
              postDate: edge.node.post_date,
            });
          }
        );
        resolve(posts);
      })
      .catch((error: any) => {
        reject(error);
      });
  });
};
}

Some things to note in this new class.

  • It's also now implementing an interface so that it can instantiated using DI.
  • The @injectable decorator allows TSyringe to inject the dependencies at runtime.
  • The constructor is decorating a parameter with @inject("graphClient") which means that parameter will be injected at runtime with whatever is configured against the graphClient token.
  • There are imports from tsyringe.
  • There are no references to the implementation of graphClient.
  • My function now has zero dependencies on Apollo Client and doesn't even know it's being used.

My implementation of graphClient looks like this.

import { autoInjectable } from "tsyringe";
import { DocumentNode } from "apollo-link";
import ApolloClient from "apollo-client";
import { NormalizedCacheObject } from "apollo-cache-inmemory";
import { graphClient } from "./iGraphQl";

@autoInjectable()
export class apolloGraphClient implements graphClient {
apolloClient: ApolloClient<NormalizedCacheObject>;

constructor(apolloClient: ApolloClient<NormalizedCacheObject>) {
  this.apolloClient = apolloClient;
}

public query = async (query: DocumentNode, variables?: {}): Promise<any> => {
  const queryOptions = {
    query: query,
    variables: variables,
  };

  return new Promise((resolve, reject) => {
    this.apolloClient
      .query(queryOptions)
      .then((response: any) => {
        resolve(response);
      })
      .catch((error: any) => {
        reject(error);
      });
  });
};
}

Essentially all this function does is pass the parameters to the query function to an Apollo Client's query function. The Apollo Client itself is also being injected!

You may have expected this file to also instantiate the Apollo Client, and it could have, but I've gone to the extreme and the single purpose of this file is to act as a bridge between the business logic queries and what client is being used, so for that reason its injected.

You'll also notice that this time I'm decorating the class with @autoInjectable() and there is no decorator on the constructor parameter. More on this in a bit.

The homepage page for this site now looks like this.

import Head from "next/head";

import React, { useState } from "react";
import { container } from "tsyringe";
import { GetStaticProps } from "next";
import Layout from "../layouts/layout";
import { FeaturedRow1, FeaturedRow1Model } from "../components/featured-row-1";
import SectionHeading from "../components/section-heading";
import { iGetLatestPosts } from "../utils/queries/iGetLatestPosts";

export default function Home({
latestPosts,
webDevelopmentPosts,
sitecorePosts,
devOpsPosts,
}: {
latestPosts: FeaturedRow1Model;
webDevelopmentPosts: FeaturedRow1Model;
sitecorePosts: FeaturedRow1Model;
devOpsPosts: FeaturedRow1Model;
}) {
return (
  <Layout>
    <Head>
      <title>Hi My Name Is Tim</title>
    </Head>
    <SectionHeading heading="Latest Posts" link="blog"></SectionHeading>
    <FeaturedRow1 posts={latestPosts}></FeaturedRow1>
    <SectionHeading heading="Web Development" link="web-development"></SectionHeading>
    <FeaturedRow1 posts={webDevelopmentPosts}></FeaturedRow1>
    <SectionHeading heading="Sitecore" link="sitecore"></SectionHeading>
    <FeaturedRow1 posts={sitecorePosts}></FeaturedRow1>
    <SectionHeading heading="Devops" link="devops"></SectionHeading>
    <FeaturedRow1 posts={devOpsPosts}></FeaturedRow1>
  </Layout>
);
}

export const getStaticProps: GetStaticProps = async () => {
// Resolve interface for iGetLatestPosts
const instance = container.resolve<iGetLatestPosts>("iGetLatestPosts");

const latestPosts = await instance.getLatestPosts();
const webDevelopmentPosts = await instance.getLatestPosts("X8kFhxIAACcAn9oY");
const devOpsPosts = await instance.getLatestPosts("X8kFlRIAACkAn9pa");
const sitecorePosts = await instance.getLatestPosts("X8kFeBIAACkAn9nV");

return {
  props: {
    latestPosts: latestPosts,
    devOpsPosts: devOpsPosts,
    sitecorePosts: sitecorePosts,
    webDevelopmentPosts: webDevelopmentPosts,
  },
};
};

Pages in NextJS TypeScript don't use classes, so we can't do constructor injection to get the instance of our getLatestPosts query class. Instead we are using container.resolve<iGetLatestPosts>("iGetLatestPosts") to get the instance to token name iGetLatestPosts from the DI container.

Lastly in the _app.tsx file I am registering the classes on the container. I'm only including the relevant bit of the file here.

container.registerInstance(
ApolloClient,
new ApolloClient({
  link: PrismicLink({
    uri: prismicGraphUri,
    repositoryName: prismicRepoName,
  }),
  cache: new InMemoryCache({ fragmentMatcher }),
})
);

container.register(&quot;graphClient&quot;, apolloGraphClient);
container.register(&quot;iGetLatestPosts&quot;, getLatestPosts);

For the Apollo Client I am using register instance to register a specific instance and creating it at the same time. Notice the first parameter is the class name.

For the graph client and getLatestPosts query I am using the register method and rather than creating the instance of my implementation, just passing the class as the second parameter. The framework will handle creating an instance of them for me.

Notice the first parameter for the second two are strings rather than the actual interfaces. These are token names that the container will use to reference the instance value. With the Apollo Client, the framework will figure out the token name when it adds it to the container, but it can't do the same for an interface (if you try you will get an interface cannot be used as a type error) so you have to provide the token name instead. This is also the reason why the graph client implementation didn't need to use a string to inject the class instance in the constructor, whereas the other places did.

Personally I feel this is a weakness in the framework as it also means there is no type checking either when registering or resolving from the container.

Summary

We have seen that using JavaScript doesn't prevent us from using the same concepts as we would with any other more traditional backend language.

We've also seen how a NextJS application while slightly more awkward, can still be set up to use dependency injections.

Finally we've had a look at how to actually configure some code to have complete separation between logic within a solution.

Data Fetching options with NextJS

When it comes to building websites in node, I'm a big fan of using NextJS. There's a lot of static site generators around but one of the things I really like about NextJS is not only the fact you have different options for data fetching, but that they're also really easy to use.

Static Generation

If you've somehow missed it, static site generation is the idea that to make your site run as fast as possible for every user, you pre-generate all the pages so that when a visitor makes a request for the page, all the server needs to do is return a file. It's a bit like the start of the internet when everything was an html file, before we became clever and started generating files dynamically on the fly. With all the processing removed, the time to first byte is greatly reduced.

To do this with NextJs you add a function called getStaticProps to your page and when the site is built, this will get all the static content and make it available to the page to be pre-generated.

export async function getStaticProps(context) {
return {
  props: {}, // will be passed to the page component as props
}
}

Or if your using TypeScript.

import { GetStaticProps } from 'next'

export const getStaticProps: GetStaticProps = async (context) => {
// ...
}

Static Generation for Dynamic Paths

So that last example would generate content for a page, but what if you have a headless CMS and unlimited pages. You certainly couldn't create a file for each one with it's own getStaticProps function.

For this there is getStaticPaths. Like getStaticProps this function will run at the build time and is used to find and return all the dynamic paths for the page. Think of your page as the page template and this function is getting all the pages that relate to it. This is how I generate all the blog post pages on this site.

The function returns an object with two values. First paths which is a list of all the routes and the parameters for them. e.g. a list of the id's to get the data for a page with. The second is fallback: false, this tells NextJs that if the request is for a route not in the paths list, then returns a 404.

export async function getStaticPaths() {
return {
  paths: [
    { params: { ... } } 
  ],
  fallback: false
};
}

The params are then passed to the getStaticProps function so that it can pre-generate all the page content.

// This also gets called at build time
export async function getStaticProps({ params }) {
// params contains the post `id`.
// If the route is like /posts/1, then params.id is 1
const res = await fetch(`https://.../posts/${params.id}`)
const post = await res.json()

// Pass post data to the page via props
return { props: { post } }
}

If you'd prefer Typescript then this is the alternative.

import { GetStaticPaths } from 'next'

export const getStaticPaths: GetStaticPaths = async () => {
// ...
}

The Good Old Dynamic Way

Static's great, but sometimes are pages just aren't static enough for it to make sense. Here's where getServerSideProps comes in. With getServerSideProps your page will get generated on the server at runtime.

At this point you head may explode because at some point someone told you static site generators were faster, more secure etc because nothing runs on the server. Well erm.................. there is a server and it can generate files, so they were er... wrong.

export async function getServerSideProps(context) {
return {
  props: {}, // will be passed to the page component as props
}
}

Or with TypeScript.

import { GetServerSideProps } from 'next'

export const getServerSideProps: GetServerSideProps = async (context) => {
// ...
}

Incremental Static Regeneration

Lets take are mind back to that first static page generation. It's great for the end user, but the downside is that each time you need to change something on a page you have to regenerate the entire site. On a big site, that's an issue.

Incremental Static Regeneration lets you tell NextJs that while you want the page the be pre-built, you also want that version to expire and get generated again. Think of this like the expiry time on a CDN, but configured at a page level in your site.

To use it the getStaticProps function needs to return a revalidate value. This gives the instruction of up to how frequently the page should be generated.

export async function getStaticProps() {
const res = await fetch('https://.../posts')
const posts = await res.json()

return {
  props: {
    posts,
  },
  // Next.js will attempt to re-generate the page:
  // - When a request comes in
  // - At most once every 10 seconds
  revalidate: 10, // In seconds
}
}

Part Static Generation

So lets say we don't need our pages to expire other than when we rebuild the site, and we also don't want to generate every page in our site because there 2000 of them and it will take ages, but there's also some really important pages that we don't want any user to have to wait for.

Well if we go back to our static generation for dynamic routes example and take another look at that fallback value we can do something different.

Fallback can be set to 3 values, false, true and blocking. False will return a 404 if the route didn't exist, but true and blocking gives us an option to decide at runtime if we want to generate a page or issue a 404.

Setting fallback to true will return a fallback page, getStaticProps will then generate the page and this will then get swapped with the fallback version. Blocking is similar but will wait for the new page to be generated rather than initially issuing a fallback.

By doing this, the paths we return in the props will get generated at build time (we can restrict this to just our important pages), and all the others will function like a regular CDN.

Summary

So as you can see, there's a whole host of options to fetching data, when you do it, how you do it, how long it lives for and I didn't even cover the fact you could still fetch data dynamically when the page has loaded on the client! If we did this then we can pre-generate all the static parts of our page and then populate other bits dynamically after on the client.

JavaScript frameworks explained to an ASP.NET dev

For most of my career I've been an ASP.NET dev and a JavaScript dev. If I was going to say I was more of an expert in one of them it would be the .NET side of things but I've never really lost touch with JavaScript.

Right now I think it's fair to say technologies in the world are starting to shift how we build websites, with JavaScript frameworks reaching a point with features like static site generation where they actually now offer a decent performance incentive to use them. At some point Blazor may get to a point where it reverses this, but right now there's a compelling argument to move.

For a ASP.NET dev this can be a daunting task. You might be thinking of trying out a headless CMS with a JavaScript front end, but just take a look at this screen grab from Prismic's sdk list.

There's 7 different JavaScript based SDK's listed there! Over half of the total and none of them are that Angular thing you had heard about. Where do you start?

Lets compare to .NET

Well recently I've been updating my JS skills again trying out some of the frameworks I hadn't used before, so I thought I'd share some learnings. The good news is as always it's not really as different as it first seems. To take some of the pain out of understanding what all these frameworks are I thought it would be good to try and relate them back to .NET and what the almost equivalent is.

Assembly Code

No not actual assembler but what does our code actually compile to. In the .NET world we have CIL (Common Intermediate Language), previously known as MSIL (Microsoft Intermediate Language) that our C#, F#, VB etc all compile down to before then being converted to the correct machine code for where they run.

In the front end world think of JavaScript being a bit like this (apart from the fact you actually write JavaScript and we don't write CIL).

View Engine

To render views into HTML, in the ASP.NET world we have Razor, but not just Razor. We also have WebForm, Brail, Bellevue, NDjango (see more here), it just happens that we mostly just use Razor.

I see the equivalents of these being ReactJS, VueJS and Angular. Its not an exact match as they also aren't exact equivalents or each other, but they're largely your functionality that will take a model and turn it into HTML.

Web Application Framework

The problem with the name framework is it applies to basically anything, but this is what I'm going with for describing ASP.NET MVC/ASP.NET Razor Pages/Web Forms, you know all those things built on-top of .NET that make it a website rather than a desktop app. They do things like routing, organising our files into controller and view folders, know how to respond to http requests etc.

Here we have Next.js, Nuxt.js and maybe Gatsby. The link between these and View Engine is a bit stronger than the ASP.NET MVC world as you essentially have a one to one mapping Next.js -> React, Nuxt.js -> Vue but they are what adds routing, static site generation and organization to your code.

Lower Level Framework

Now this one could be wrong :)

In .NET we have different version of the framework. e.g. .NET Framework /3.5/4, .NET Core, .NET 5, Mono. On the front end side they have Node.

Languages

In .NET we have choices including C#, F#, VB among other.

JavaScript has JavaScript (which I know I said was assembly), TypeScript, Coffee Script maybe more.

Not so daunting

There's probably a bunch of flaws with my comparison list and reasons people can point out why things I've said are the same are in fact different, but my point was really to show that while .NET may appear as one button on a SDK list alongside 7 JavaScript based SDK's its not that different. Out of the 7 Node is based on JavaScript. Vue and React are based on Node, and Next/Gatsby/Nuxt are based on Vue/React. There just isn't the same concept of all of it being built by one company or one particular combination being dominant in the same way that ASP.NET MVC + C# + Razor has been for the last generation of .NET websites.