Web Development
Debugging VueJS + TypeScript with VS Code - Part 2

Debugging VueJS + TypeScript with VS Code - Part 2

In the past I have written about how to setup VS Code to debug a VueJS + TypeScript project. Since writing that article it's a method I've continued to use and it works well. It's quick to spin up and quite reliably allows you to place breakpoints in code.

However one aspect of it that I don't like is it's not so much "Run and Debug" from VSCode, it's more just the debug part, as to use it you must first go to a terminal and run your VueJS application.

There's two problems with this:

1. Most of the time you will just run the application not debugging (because why debug when you don't have an issue), therefore when you need it, you have to redo what you just did that caused an error. Instinctively there is then a desire to guess at what was wrong rather than going to the extra effort of debugging (frequently when you do this your guess is wrong and you end up spending more time guessing at what was wrong than using the tool that will tell you).

2. As the debugger generally isn't running, exceptions never get flagged up, and unless you have the browser console open (and check it), you can remain oblivious to something going wrong in your app.

There is a solution though, and it's quite simple!

Using VS Code to launch via npm

First follow through my previous guide on debugging a VueJS and TypeScript application.

Next, in your launch.config file add a new configuration with the definition below. This will run the command in a debug terminal, effectively doing the same thing as you typing npm run serve.

1{
2 "command": "npm run serve",
3 "name": "Run npm serve",
4 "request": "launch",
5 "type": "node-terminal"
6 },

To get both our new and old configuration to run you can add a compound definition, that does both at the same time.

Here's mine.

1"compounds": [
2 {
3 "name": "Run and Debug",
4 "configurations": ["Run npm serve", "vuejs: edge"]
5 }
6 ],

My complete file now looks like this. Note you don't need configurations for edge and chrome, just use the one for the browser you use.

1{
2 // Use IntelliSense to learn about possible attributes.
3 // Hover to view descriptions of existing attributes.
4 // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5 "version": "0.2.0",
6 "compounds": [
7 {
8 "name": "Run and Debug",
9 "configurations": ["Run npm serve", "vuejs: edge"]
10 }
11 ],
12 "configurations": [
13 {
14 "command": "npm run serve",
15 "name": "Run npm serve",
16 "request": "launch",
17 "type": "node-terminal"
18 },
19 {
20 "type": "pwa-msedge",
21 "request": "launch",
22 "name": "vuejs: edge",
23 "url": "http://localhost:8080",
24 "webRoot": "${workspaceFolder}",
25 "breakOnLoad": true,
26 "sourceMapPathOverrides": {
27 "webpack:///./*": "${webRoot}/*"
28 },
29 "skipFiles": ["${workspaceFolder}/node_modules/**/*"]
30 },
31 {
32 "type": "chrome",
33 "request": "launch",
34 "name": "vuejs: chrome",
35 "url": "http://localhost:8080",
36 "webRoot": "${workspaceFolder}",
37 "breakOnLoad": true,
38 "sourceMapPathOverrides": {
39 "webpack:///./*": "${webRoot}/*"
40 },
41 "skipFiles": ["${workspaceFolder}/node_modules/**/*"]
42 }
43 ]
44}
45

Now whenever you want to run the application, just run the compound Run and Debug and your VueJS app will start up and launch in your browser.

Which JavaScript for loop should I use?

Which JavaScript for loop should I use?

When given a choice of 4 seemingly different ways to do the same thing, I've always been the person that wants to know what the difference is? To often we can blindly write code the way the person before us did and not understand the reason to do it a certain way, but what if the scenario has changed. When multiple options exist there's usually a reason why. It can be a language style improvement to make things easier to write, but more often than not there's a fundamental difference in what it actually does.

So, for loops, four seems like a lot, gotta be some differences right?

for

This is likely to be the first type of for loop you encounter when learning to program. It's a very manual type of loop where you create a initial expression, a condition expression to keep running the loop and an increment expression.

1for (let i = 0; i < 5; i++) {
2 console.log(i);
3}
4
5// Result:
6// 0
7// 1
8// 2
9// 3
10// 4

The big downside of the for loop is it doesn't actually loop through a collection. e.g. If you had an array and wanted to loop through each of it's objects you could do this as follows:

1const arr = ['a', 'b', 'c'];
2
3for (let i = 0; i < arr.length; ++i) {
4 console.log(arr[i]);
5}

In effect the loop is incrementing a number and you then use that number to access the position of the array. The result is you have more code to write that isn't serving any real purpose.

However as this is a much more manual loop process you have far more control over the loop. e.g.

  • You could increment by a different number.
  • You could go backwards.
  • The condition might not be linked to the length of an array.
  • You might not even be looping through an array.

Pros

  • Potentially faster in performance.
  • Break statement can be used to come out of the loop.
  • It works with the await keyword.
  • Not just for looping through arrays.

Cons

  • Not as readable as others.
  • You have more code to write.

for...in

You probably don't want this one. Here's an example:

1const arr = ['a', 'b', 'c'];
2
3for (const i in arr) {
4 console.log(arr[i]);
5}
6
7// Result:
8// "a"
9// "b"
10// "c"

Although we're now specifically looping through a collection like an array and don't need to do all of that i < array.length stuff, what we're given isn't the object in the array but a property name to access it on the object.

Here's another example:

1const arr = ['a', 'b', 'c'];
2arr.foo = 'John'
3
4for (const i in arr) {
5 console.log(arr[i]);
6}
7
8// Result:
9// "a"
10// "b"
11// "c"
12// "John"

That looks a bit weird! The for...in loop doesn't just loop through an array, it loops through an objects enumerable properties, which could be the items in an array, but it could be other stuff too.

For this reason, unless your doing something quite niche its probably not the loop you are looking for and is likely to cause you an issue which your objects has one more property than you were expecting.

Pros

  • Can loop through all the enumerable properties on an object.

Cons

  • Looping through all the properties of an object isn't likely what you want.

forEach

As the name implies, a for each loop will iterate through each element in an array. Here's an example:

1const arr = ['a', 'b', 'c'];
2
3arr.forEach((i) => {
4 console.log(i);
5})
6
7// Result:
8// "a"
9// "b"
10// "c"

The forEach function takes an anonymous function as a parameter and will then call that function for each object in the array, passing in the object from the array.

This offers a big improvement over the initial for loop as we have a lot less code to write and we're actually given the object rather than a variable to go an find it.

However there are some downsides due to it effectively being a function call passing an anonymous function to execute.

Firstly you can't stop the forEach part way through. With the others you can use the break keyword to stop the iteration.

Secondly there's added confusion around the scope of what this is. Assuming your function is in a class, unless you use the arrow syntax (as in the example) you won't be able to access any of the other functions in your class as passing a regular function would change the scope.

1// This works
2class foo
3{
4 myFunction() {
5 const arr = ['a', 'b', 'c'];
6
7 arr.forEach((i) => {
8 this.outputValue(i)
9 })
10 }
11
12 outputValue(x) {
13 console.log(x);
14 }
15}
16
17// This Doesn't
18class foo
19{
20 myFunction() {
21 const arr = ['a', 'b', 'c'];
22
23 arr.forEach(function(i) {
24 this.outputValue(i)
25 })
26 }
27
28 outputValue(x) {
29 console.log(x);
30 }
31}

You also can't use an await within the foreach loop. e.g.

1async function run() {
2 const arr = ['a', 'b', 'c'];
3 arr.forEach(el => {
4 // SyntaxError
5 await new Promise(resolve => setTimeout(resolve, 1000));
6 console.log(el);
7 });
8}

Pros

  • Much shorter to write and easier to read.
  • Iterator provides the object from the array.

Cons

  • Easy to mess up context of this.
  • No way to break the loop.
  • Async/Await doesn't work on functions within the loop.
  • Can only loop through arrays.
  • It's performance is slower (nice article here comparing the performance differences), not to such an extent it would matter on a small object, but large objects could start to take a hit.

for...of

When looping through an array, the for...of loop combines the best of all the other loops. It has the same simple syntax of the for...in loop but instead of enumerating over enumerable properties, it loops through the iterable objects such as the items in an array.

Like the forEach loop you are provided with the object in the array rather than it's index or property name.

1const arr = ['a', 'b', 'c'];
2
3for (const i of arr) {
4 console.log(i);
5}
6
7// Result:
8// "a"
9// "b"
10// "c"

You can also break the loop and access properties outside of the loop.

1const stopValue = 'b'
2const arr = ['a', 'b', 'c'];
3
4for (const i of arr) {
5 console.log(i);
6 if (i == stopValue)
7 break;
8}
9
10// Result:
11// "a"
12// "b"

Pros

  • Lowest amount of extra code to write.
  • Iterator provides the object.
  • Doesn't use an anonymous function so scope doesn't change.
  • Loop can be stopped as needed.
  • Async still works.
  • Works with more than just arrays.

Cons

  • Have to be looping over the iterable items in an object.
  • Can't easily access the index value.

Conclusion

If you want to iterate through something like an array, for...of would be my recommendation to use. A for...in loop is likely to be less relevant but has its place, and for all other loops which don't relate to the objects in an array a good old for loop still has it's place.

Dependency Injection with NextJS and TypeScript

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.

1import gql from 'graphql-tag';
2import { Client, ApolClient } from '../prismicHelpers'
3
4// Models
5import { FeaturedPost } from "../../Models/FeaturedPost"
6
7const latestPostsQuery = gql`
8query latestPosts($category: String) {
9 allPosts (where : {category: $category}, first : 10, sortBy: post_date_DESC){
10 edges {
11 node {
12 category {
13 ... on Categories {
14 name
15 }
16 },
17 title,
18 image,
19 post_date
20 _meta {
21 uid
22 }
23 }
24 }
25 }
26}
27`;
28
29export const getLatestPosts = async (category?: String) : Promise<FeaturedPost[]> => {
30 const queryOptions = {
31 query: latestPostsQuery,
32 variables: { category },
33 };
34
35 return new Promise((resolve, reject) => { ApolClient.query(queryOptions).then(response => {
36 var posts: Array<FeaturedPost> = [];
37 response.data.allPosts.edges.map((edge: { node: { title: { text: any; }[]; category: any; image: any; post_date: Date; _meta: { uid: any; }; }; }, key: any) => {
38 posts.push({
39 type: "post",
40 title: edge.node.title[0].text,
41 image: edge.node.image,
42 uid: edge.node._meta.uid,
43 category: edge.node.category?.name,
44 postDate: edge.node.post_date
45 })
46 })
47 resolve( posts);
48 }).catch(error => {
49 reject(error);
50 });
51});
52};

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.

1npm install --save tsyringe reflect-metadata

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

1{
2 "compilerOptions": {
3 "experimentalDecorators": true,
4 "emitDecoratorMetadata": true
5 }
6}

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.

1npm 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.

1{
2 "presets": ["next/babel"],
3 "plugins": [
4 "babel-plugin-transform-typescript-metadata",
5 ["@babel/plugin-proposal-decorators", { "legacy": true }],
6 ["@babel/plugin-proposal-class-properties", { "loose": true }]
7 ]
8}

Finally add this import to your _app.tsx file.

1import "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.

1import { DocumentNode } from "graphql";
2
3export interface graphClient {
4 query(query: DocumentNode, variables?: {}): any;
5}

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

1import { inject, injectable } from "tsyringe";
2import { iGetLatestPosts } from "./iGetLatestPosts";
3import gql from "graphql-tag";
4import { graphClient } from "../iGraphQl";
5
6// Models
7import { FeaturedPost } from "../../Models/FeaturedPost";
8
9@injectable()
10export class getLatestPosts implements iGetLatestPosts {
11 graphClient: graphClient;
12
13 constructor(@inject("graphClient") private graphClientParam: graphClient) {
14 this.graphClient = graphClientParam;
15 }
16
17 private latestPostsQuery = gql`
18 query latestPosts($category: String) {
19 allPosts(
20 where: { category: $category }
21 first: 10
22 sortBy: post_date_DESC
23 ) {
24 edges {
25 node {
26 category {
27 ... on Categories {
28 name
29 }
30 }
31 title
32 image
33 post_date
34 _meta {
35 uid
36 }
37 }
38 }
39 }
40 }
41 `;
42
43 public getLatestPosts = async (
44 category?: String
45 ): Promise<FeaturedPost[]> => {
46 return new Promise((resolve, reject) => {
47 this.graphClient
48 .query(this.latestPostsQuery, { category })
49 .then((response: any) => {
50 var posts: Array<FeaturedPost> = [];
51 response.data.allPosts.edges.map(
52 (
53 edge: {
54 node: {
55 title: { text: any }[];
56 category: any;
57 image: any;
58 post_date: Date;
59 _meta: { uid: any };
60 };
61 },
62 key: any
63 ) => {
64 posts.push({
65 type: "post",
66 title: edge.node.title[0].text,
67 image: edge.node.image,
68 uid: edge.node._meta.uid,
69 category: edge.node.category?.name,
70 postDate: edge.node.post_date,
71 });
72 }
73 );
74 resolve(posts);
75 })
76 .catch((error: any) => {
77 reject(error);
78 });
79 });
80 };
81}

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.

1import { autoInjectable } from "tsyringe";
2import { DocumentNode } from "apollo-link";
3import ApolloClient from "apollo-client";
4import { NormalizedCacheObject } from "apollo-cache-inmemory";
5import { graphClient } from "./iGraphQl";
6
7@autoInjectable()
8export class apolloGraphClient implements graphClient {
9 apolloClient: ApolloClient<NormalizedCacheObject>;
10
11 constructor(apolloClient: ApolloClient<NormalizedCacheObject>) {
12 this.apolloClient = apolloClient;
13 }
14
15 public query = async (query: DocumentNode, variables?: {}): Promise<any> => {
16 const queryOptions = {
17 query: query,
18 variables: variables,
19 };
20
21 return new Promise((resolve, reject) => {
22 this.apolloClient
23 .query(queryOptions)
24 .then((response: any) => {
25 resolve(response);
26 })
27 .catch((error: any) => {
28 reject(error);
29 });
30 });
31 };
32}

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.

1import Head from "next/head";
2
3import React, { useState } from "react";
4import { container } from "tsyringe";
5import { GetStaticProps } from "next";
6import Layout from "../layouts/layout";
7import { FeaturedRow1, FeaturedRow1Model } from "../components/featured-row-1";
8import SectionHeading from "../components/section-heading";
9import { iGetLatestPosts } from "../utils/queries/iGetLatestPosts";
10
11export default function Home({
12 latestPosts,
13 webDevelopmentPosts,
14 sitecorePosts,
15 devOpsPosts,
16}: {
17 latestPosts: FeaturedRow1Model;
18 webDevelopmentPosts: FeaturedRow1Model;
19 sitecorePosts: FeaturedRow1Model;
20 devOpsPosts: FeaturedRow1Model;
21}) {
22 return (
23 <Layout>
24 <Head>
25 <title>Hi My Name Is Tim</title>
26 </Head>
27 <SectionHeading heading="Latest Posts" link="blog"></SectionHeading>
28 <FeaturedRow1 posts={latestPosts}></FeaturedRow1>
29 <SectionHeading heading="Web Development" link="web-development"></SectionHeading>
30 <FeaturedRow1 posts={webDevelopmentPosts}></FeaturedRow1>
31 <SectionHeading heading="Sitecore" link="sitecore"></SectionHeading>
32 <FeaturedRow1 posts={sitecorePosts}></FeaturedRow1>
33 <SectionHeading heading="Devops" link="devops"></SectionHeading>
34 <FeaturedRow1 posts={devOpsPosts}></FeaturedRow1>
35 </Layout>
36 );
37}
38
39export const getStaticProps: GetStaticProps = async () => {
40 // Resolve interface for iGetLatestPosts
41 const instance = container.resolve<iGetLatestPosts>("iGetLatestPosts");
42
43 const latestPosts = await instance.getLatestPosts();
44 const webDevelopmentPosts = await instance.getLatestPosts("X8kFhxIAACcAn9oY");
45 const devOpsPosts = await instance.getLatestPosts("X8kFlRIAACkAn9pa");
46 const sitecorePosts = await instance.getLatestPosts("X8kFeBIAACkAn9nV");
47
48 return {
49 props: {
50 latestPosts: latestPosts,
51 devOpsPosts: devOpsPosts,
52 sitecorePosts: sitecorePosts,
53 webDevelopmentPosts: webDevelopmentPosts,
54 },
55 };
56};

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.

1container.registerInstance(
2 ApolloClient,
3 new ApolloClient({
4 link: PrismicLink({
5 uri: prismicGraphUri,
6 repositoryName: prismicRepoName,
7 }),
8 cache: new InMemoryCache({ fragmentMatcher }),
9 })
10);
11
12container.register("graphClient", apolloGraphClient);
13container.register("iGetLatestPosts", 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

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.

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

Or if your using TypeScript.

1import { GetStaticProps } from 'next'
2
3export const getStaticProps: GetStaticProps = async (context) => {
4 // ...
5}

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.

1export async function getStaticPaths() {
2 return {
3 paths: [
4 { params: { ... } }
5 ],
6 fallback: false
7 };
8}

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

1// This also gets called at build time
2export async function getStaticProps({ params }) {
3 // params contains the post `id`.
4 // If the route is like /posts/1, then params.id is 1
5 const res = await fetch(`https://.../posts/${params.id}`)
6 const post = await res.json()
7
8 // Pass post data to the page via props
9 return { props: { post } }
10}

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

1import { GetStaticPaths } from 'next'
2
3export const getStaticPaths: GetStaticPaths = async () => {
4 // ...
5}

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.

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

Or with TypeScript.

1import { GetServerSideProps } from 'next'
2
3export const getServerSideProps: GetServerSideProps = async (context) => {
4 // ...
5}

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.

1export async function getStaticProps() {
2 const res = await fetch('https://.../posts')
3 const posts = await res.json()
4
5 return {
6 props: {
7 posts,
8 },
9 // Next.js will attempt to re-generate the page:
10 // - When a request comes in
11 // - At most once every 10 seconds
12 revalidate: 10, // In seconds
13 }
14}

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.