NextJS with Strapi Setup

Asit Kumar Panda5 min read
NextJS with Strapi Setup

Installation and Configuration:-

1. Next js setup

a. Create a nextJS application using “npx create-next-app@latest” and then you need to answer the following

  • What is your project named?  My-app
  • Would you like to use TypeScript?  No / Yes
  • Would you like to use ESLint?  No / Yes
  • Would you like to use Tailwind CSS?  No / Yes
  • Would you like to use `src/` directory?  No / Yes
  • Would you like to use App Router? (recommended)  No / Yes
  • Would you like to customize the default import alias (@/*)?  No / Yes

b. Once you’ve answered the prompts, a new project will be created with the correct configuration depending on your answers.

c. Note: For more information regarding nextJS you can refer to the official documentation.
    https://nextjs.org/docs/pages/api-reference/create-next-app

d. To start the Next Js application we can run the following commands.

  • npm run dev 
           or
  • yarn dev

e. Then, Open http://localhost:3000 with your browser to see the result.

2. Create a Strapi application

  • npx create-strapi-app@latest my-project --quickstart
                                    or
  • yarn create strapi-app my-project --quickstart

a. To start the strapi application in development mode,  we need to cd to the project directory and then

  • npm run develop
            or
  • yarn develop

b. This will start the strapi application development server.

c. The admin panel of Strapi runs at http://localhost:1337/admin. This is where we will spend most of your time creating and updating content.

d. Once we are logged in to the Strapi dashboard we can start building collections from the content-type-builder. A collection literally is a schema for a table in the database.

e. When we create a collection in the content-type-builder it will automatically create some crud APIs(get, post, put, delete) for the collection with all the possible filters and pagination.

f. There is a swagger documentation plugin, we can install inside our Strapi application and it will give us a documentation section in the admin dashboard. This swagger documentation will contain the list of APIs that are available for the Strapi application.

g. For more information regarding the Strapi setup we can view the documentation of Strapi.
https://docs.strapi.io/dev-docs/quick-start

3. How to use Next JS for building a static website.

a. Export to static website:- First we need to build the application

  • npm run build
    then,
  • npm run export

b. This allows you to export your Next.js application to static HTML, which can be run standalone without the need for a Node.js server. All the static HTML files will be generated inside the out directory at the root of the application.

c. Dynamic page generation is possible in NextJS, i.e. we can generate static pages based on the data that we are getting from the backend via API call. But we should be able to pre-render a page at build time.

d. To make network calls in the Next application during the build we can use getStaticProps, we can use to make the network call during the build time itself and we can pass the data to the page component as params and we can decide which custom components to render inside the page based on the data that we got from the backend.

Example: -

    export async function getStaticProps({ params }: any) {
    const siteConfig = await getSiteConfig();
       return {
        props: {configs: siteConfig },
      };
    }

    export default function Home({ config}: any) {
      const router = useRouter();
      if (!router.isFallback && !config) {
        return <ErrorPage statusCode={404} />;
      }
      // We can use the config here inside the 
      return (
      // UI code here ..
    )}

Explanation

  1. In the above example the getStaticprops get called at the build time only and will return an object with “props” e.g {props: <some value>}.
  2. We can use the props in the screen by accepting them as params to the function. In the above example, we will have the config values available during the mounting it self as we are getting the values during the build.
  3. Learn More https://nextjs.org/docs/pages/api-reference/functions/get-static-props

4. How to do dynamic page generation

In the above example, we learned how to get data during build so that when we export the code for a static build it will have the required values for the screen.

  1. Now we’ll see how we can generate a file/folder dynamically based on the condition/requirement.
  2. We can take an example of creating a webpage in multiple locales i.e we need to create a page in multiple languages so when we change the language on the website it’ll load the page of that specific locale.
  3. Example:-
	// This is the method to get the data from the backend during the build time. Returns props.
	export async function getStaticProps({ params }: any) {
   	  const config = await getSiteConfig(params.locale);
  	  return {
    	    props: {configs: config },
  	  };
	}

	// This is the method that gets the locale data from the backend and returns paths,
	// the list of paths to be created dynamically.
	export async function getStaticPaths() {
  	  const localeConfig = await getLocaleConfig();
  	  return {
    	    paths: localeConfig?.map((item) => `/dynamic/${item.attributes.locale}`) || [],
    	    fallback: false,
  	  };
	}

	export default function Page({ config, pages }: any) {
  	  const router = useRouter();
  	  if (!router.isFallback && !config[0]) {
    	    return <ErrorPage statusCode={404} />;
  	  }
  	  const defalut: Config = config[0];
 	  return (
	     // UI code for the 
	  )
	}

Explanation:

In the above example, we have used the getStaticPaths method to define the dynamic routes. In this method, we are getting all the locale information from the backend and then we are returning an object containing “paths”, “paths“ contains an array of the paths.

  1. During build time the getStaticPaths will execute and it will return the dynamic paths i.e. the files for the path name will be created. 
  2. For the files to be dynamically created we need to define file name in a format like this:- [locale].tsx.
  3. So during build it will create files like en.tsx, po.tsx, fr.tsx etc, if we are getting en(English), po(polish), and fr(french) locales inside the getStaticPaths.

Note: Here in the example we can use APIs created on Strapi and we can have a dynamic page and content setup inside our next application. As Strapi is a headless CMS, we can edit our website config and contents from Strapi dashboard.

Ready to build something that matters?

We solve problems that don't have Stack Overflow answers. Let's talk.

Book a Discovery Call