# How to use Next.js on the frontend

**URL:** <https://forum.dfinity.org/t/how-to-use-next-js-on-the-frontend/17545>\
**Category:** Developers\
**Created:** [December 19, 2022, 11:57am UTC](https://forum.dfinity.org/t/how-to-use-next-js-on-the-frontend/17545 "2022-12-19T11:57:15Z")\
**Posts on this page:** 15\
**Page:** 1

<div class="post-metadata">

**Author:** ![yk-saito](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/yk-saito/32/7196_2.png) [@yk-saito](https://forum.dfinity.org/u/yk-saito)\
**Post date:** [December 19, 2022, 11:57am UTC](https://forum.dfinity.org/t/how-to-use-next-js-on-the-frontend/17545/1 "2022-12-19T11:57:15Z")

</div>

Hello!

I am looking to use Next.js for my front end.  
I have created a project using npx create and imported the files generated by dfx new (the backend is Rust).

> **[GitHub - dappblock/nextjs-ic-starter: Next.js Internet Computer Starter Template](https://github.com/dappblock/nextjs-ic-starter)**
>
> Next.js Internet Computer Starter Template. Contribute to dappblock/nextjs-ic-starter development by creating an account on GitHub.

I finally got dfx deploy to work, but when I connect to the front end, I get a “not found” message.

 ![Screen Shot 2022-12-19 at 20.40.36](https://us1.discourse-cdn.com/flex023/uploads/dfn/original/2X/8/83610daf87c1d26fb5552666ace42f69649b2e55.png)

I hope someone can help me.

[Here](https://github.com/yk-saito/encrypted_notes_nextjs/tree/env-backend) is the repository with all the source code.

Currently, we have not yet implemented the connection between the front end and the back end. First of all, I would like to be able to deploy the front end to the dfx local environment.

---

<div class="post-metadata">

**Author:** ![infu](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/infu/32/11321_2.png) [@infu](https://forum.dfinity.org/u/infu)\
**Post date:** [December 19, 2022, 12:26pm UTC](https://forum.dfinity.org/t/how-to-use-next-js-on-the-frontend/17545/2 "2022-12-19T12:26:33Z")

</div>

Next.js is producing static files. If you get a simple index.html working, then next.js should work too.  
What happens is, all static files get uploaded to an asset canister.  
The problem may be, that next.js is trying to figure out your page from the URL and there is nothing matching `?canisterid=ry....`  
It will work if you are using `npm run dev` without trying to locally deploy it. You can still connect it to the IC local backend, while the dev frontend gets served by a bundler, not local replica. (That’s what I am doing with my projects - for faster reloading when changing code)  
Once you deploy it on IC in production, URLs will fix and it should work.

If you want to point a local domain to a canister, so your URLs work without `?canisterId`, then you can use icproxy. Something like this

```auto
icx-proxy --address 127.0.0.1:8453 --dns-alias 0.lvh.me:rno2w-sqaaa-aaaaa-aaacq-cai

```

`anything.lvh.me` will point to 127.0.0.1 and you can change ‘anything’

---

<div class="post-metadata">

**Author:** ![yk-saito](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/yk-saito/32/7196_2.png) [@yk-saito](https://forum.dfinity.org/u/yk-saito)\
**Post date:** [December 19, 2022, 2:50pm UTC](https://forum.dfinity.org/t/how-to-use-next-js-on-the-frontend/17545/3 "2022-12-19T14:50:30Z")

</div>

Thanks for your response.  
Indeed, `npm run dev` gives me access to the front end.

Now, when I try to call the backend code, I get the following error Perhaps there is something wrong with the way the environment variables are set…

```bash
error - Error: Must specify a host to connect to.
    at new HttpAgent 
    at createActor (webpack-internal:///./src/declarations/backend/index.js:18:36)
    at eval (webpack-internal:///./src/declarations/backend/index.js:38:17)
    at Object../src/declarations/backend/index.js 
    at __webpack_require__ 
    at eval (webpack-internal:///./src/service/actor.ts:6:79)
    at Object../src/service/actor.ts 
    at __webpack_require__ 
    at eval (webpack-internal:///./src/container/Greeting.tsx:7:71)
    at Object../src/container/Greeting.tsx {
  page: '/'
}

```

I understand that this is implemented using Next.js, but if you have a repository, etc., I would love to see it. I’d love to use it as a reference for my build 🙂!

---

<div class="post-metadata">

**Author:** ![infu](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/infu/32/11321_2.png) [@infu](https://forum.dfinity.org/u/infu)\
**Post date:** [December 19, 2022, 8:21pm UTC](https://forum.dfinity.org/t/how-to-use-next-js-on-the-frontend/17545/4 "2022-12-19T20:21:50Z")

</div>

The error shows because the frontend can’t connect to the backend. I havent used this repo nor rust. If it was me, I would start with clean nextjs and then just add one dfx.json with the frontend can. Then dfx deploy will work.  
Everything backend, I would prefer to write in Motoko.

I guess the real reason one would prefer Nextjs over Create-react-app is because it generates static HTML files that search engines can crawl. This starter kit is not demonstrating that.  
So the question is, what do you really want to do. Are you planning on relying on indexable website or do you want to create an application? If it’s the second, just use React CRA.

---

<div class="post-metadata">

**Author:** ![skilesare](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/skilesare/32/5609_2.png) [@skilesare](https://forum.dfinity.org/u/skilesare)\
**Post date:** [December 20, 2022, 4:32am UTC](https://forum.dfinity.org/t/how-to-use-next-js-on-the-frontend/17545/5 "2022-12-20T04:32:38Z")

</div>

Axon is a next.js app…it might have some clues. GitHub/floorlamp/axon I think.

---

<div class="post-metadata">

**Author:** ![peterparker](https://avatars.discourse-cdn.com/v4/letter/p/b9bd4f/32.png) [@peterparker](https://forum.dfinity.org/u/peterparker)\
**Post date:** [December 20, 2022, 5:51am UTC](https://forum.dfinity.org/t/how-to-use-next-js-on-the-frontend/17545/6 "2022-12-20T05:51:04Z")

</div>

> [@yk-saito](#):
>
> Now, when I try to call the backend code, I get the following error Perhaps there is something wrong with the way the environment variables are set…
> 
> ```auto
> error - Error: Must specify a host to connect to.
> 
> ```

The error most probably happens when Next.js prerender your app - i.e. this error find place because the prerendering of your app happens in a NodeJS context (on the server side) and not in a browser context where agent-js uses the `window` object to determine the host to connect to.

If you do not want or need to prerender the data provided by the IC to build your app, you can either lazy load the service that loads the data only on the client side or dynamically import the components that access the IC to skip the fetching of the data.

In both case, the tricks is to not `import` the part that should not be prerendered.

Lazy load service:

```auto
// Pseudo code snippet
const isBrowser = () => typeof window !== `undefined`;

if (isBrowser) {
  const {myFunc} = await import("/path/to/service");
  myFunc()
}

```

Next dynamic import with `ssr: false` (more in doc [https://nextjs.org/docs/advanced-features/dynamic-import](https://nextjs.org/docs/advanced-features/dynamic-import))

```auto
import dynamic from 'next/dynamic'

const DynamicHeader = dynamic(() => import('../components/header'), {
  ssr: false,
})

```

---

<div class="post-metadata">

**Author:** ![yk-saito](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/yk-saito/32/7196_2.png) [@yk-saito](https://forum.dfinity.org/u/yk-saito)\
**Post date:** [December 21, 2022, 6:59am UTC](https://forum.dfinity.org/t/how-to-use-next-js-on-the-frontend/17545/7 "2022-12-21T06:59:02Z")

</div>

> [@infu](#):
>
> Next.js is producing static files. If you get a simple index.html working, then next.js should work too.  
> What happens is, all static files get uploaded to an asset canister.

My understanding of the part about using static files was unclear: I specified the file generated by running `next export` during the `next build` in dfx.json, set the entry point, and was able to access it from local. Thank you!

---

<div class="post-metadata">

**Author:** ![yk-saito](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/yk-saito/32/7196_2.png) [@yk-saito](https://forum.dfinity.org/u/yk-saito)\
**Post date:** [December 21, 2022, 6:59am UTC](https://forum.dfinity.org/t/how-to-use-next-js-on-the-frontend/17545/8 "2022-12-21T06:59:43Z")

</div>

Thanks for sharing! I will refer to it.

---

<div class="post-metadata">

**Author:** ![yk-saito](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/yk-saito/32/7196_2.png) [@yk-saito](https://forum.dfinity.org/u/yk-saito)\
**Post date:** [December 21, 2022, 2:17pm UTC](https://forum.dfinity.org/t/how-to-use-next-js-on-the-frontend/17545/9 "2022-12-21T14:17:27Z")

</div>

Thanks for the feedback!

I just used dynamic and now I can call the function!

[index.tsx]

```typescript
import dynamic from 'next/dynamic';
import styles from '../styles/Home.module.css';

const WhoamiButton = dynamic(() => import( '../components/WhoamiButton'),{ssr:false})

export default function Home() {
  return (
    <div>
      <main className={styles.main}>
        <h1 className="text-red-500">
          <WhoamiButton></WhoamiButton>
        </h1>
      </main>
    </div>
  );
}

```

[WhoamiButton.tsx]

```typescript
import Button from './Button'
import {backend} from '../../declarations/backend'

function whoami() {
  const whoami = backend.whoami()

  alert(`whoami: ${whoami}`)

  console.log(`whoami: ${whoami}`)
}

const WhoamiButton = () => {
  return (
    <Button onClick={whoami}>whoami</Button>
  )
}

export default WhoamiButton

```

I have one question here.

When I connected to the local replica, there was no error message,

 ![Screen Shot 2022-12-21 at 23.07.15](https://us1.discourse-cdn.com/flex023/uploads/dfn/original/2X/e/e03049f30a30aca2ea39660e7ead8135a04f7f5a.png)

but with the next env(localhost:3000), I get an error message after calling the function (pushing the button).

 ![Screen Shot 2022-12-21 at 23.08.47](https://us1.discourse-cdn.com/flex023/uploads/dfn/original/2X/5/58f4ca23c346386819c9783e2969afecf9a987cc.jpeg)

Do you know why this error occurs 🤔?

---

<div class="post-metadata">

**Author:** ![peterparker](https://avatars.discourse-cdn.com/v4/letter/p/b9bd4f/32.png) [@peterparker](https://forum.dfinity.org/u/peterparker)\
**Post date:** [December 21, 2022, 7:36pm UTC](https://forum.dfinity.org/t/how-to-use-next-js-on-the-frontend/17545/10 "2022-12-21T19:36:00Z")

</div>

hard to tell but I guess the proxy that should route the calls to the local replica (localhost:3000 → 127.0.0.1:4943) is not set. never tried Next.js with agent my self, so really not sure but I would search in that direction if I had to debug

side node: note the issue but `whoami` returns a promise

```auto
function async whoami() {
  const whoami = await backend.whoami()

  ...

```

---

<div class="post-metadata">

**Author:** ![infu](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/infu/32/11321_2.png) [@infu](https://forum.dfinity.org/u/infu)\
**Post date:** [December 22, 2022, 12:47pm UTC](https://forum.dfinity.org/t/how-to-use-next-js-on-the-frontend/17545/11 "2022-12-22T12:47:40Z")

</div>

It may be better if you just edit the declarations/…did.js and remove the export at the very bottom

 ![image](https://us1.discourse-cdn.com/flex023/uploads/dfn/original/2X/a/a02e4ed49eb76e90403be17966a49e752756cb2d.png)  
You will now have to create your actor when you need it, so there won’t be a need to dynamically import.

---

<div class="post-metadata">

**Author:** ![peterparker](https://avatars.discourse-cdn.com/v4/letter/p/b9bd4f/32.png) [@peterparker](https://forum.dfinity.org/u/peterparker)\
**Post date:** [December 22, 2022, 1:50pm UTC](https://forum.dfinity.org/t/how-to-use-next-js-on-the-frontend/17545/12 "2022-12-22T13:50:52Z")

</div>

Cool to know I am not the only one removing it @infu! Have you upvoted [https://github.com/dfinity/sdk/discussions/2761](https://github.com/dfinity/sdk/discussions/2761) ?

For those interested, meanwhile, I’ve got an ugly script that I run after generation of the types to perform such clean up. If it can be useful to some, there you go:

```auto
const cleanTypes = async ({ dest = `./src/declarations` }) => {
	const promises = readdirSync(dest).map(
		(dir) =>
			new Promise(async (resolve) => {
				const indexPath = join(dest, dir, 'index.js');

				if (!existsSync(indexPath)) {
					resolve();
					return;
				}

				const content = await readFile(indexPath, 'utf-8');
				const clean = content
					.replace(/export const \w* = createActor\(canisterId\);/g, '')
					.replace(/export const canisterId = process\.env\.\w*_CANISTER_ID;/g, '');

				await writeFile(indexPath, clean, 'utf-8');

				resolve();
			})
	);

	await Promise.all(promises);
};

(async () => {
	try {
		await cleanTypes({});

		console.log(`Types declarations processed!`);
	} catch (err) {
		console.error(`Error while processing the types declarations.`, err);
	}
})();

```

Note: above script also removes `canisterId` because in my dapps it leads to conflicts

---

<div class="post-metadata">

**Author:** ![infu](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/infu/32/11321_2.png) [@infu](https://forum.dfinity.org/u/infu)\
**Post date:** [December 24, 2022, 3:46pm UTC](https://forum.dfinity.org/t/how-to-use-next-js-on-the-frontend/17545/13 "2022-12-24T15:46:10Z")

</div>

Yeah. I actually leave the original files alone and create& use another file outside ‘declarations’ where I am changing a lot of things.  
Instead of all being named and exported as ‘createActor’ and later imported and renamed, I am just naming them something like createSomethingActor

---

<div class="post-metadata">

**Author:** ![peterparker](https://avatars.discourse-cdn.com/v4/letter/p/b9bd4f/32.png) [@peterparker](https://forum.dfinity.org/u/peterparker)\
**Post date:** [December 24, 2022, 4:28pm UTC](https://forum.dfinity.org/t/how-to-use-next-js-on-the-frontend/17545/14 "2022-12-24T16:28:12Z")

</div>

Same here 😃👍

e.g.

```auto
import {Actor, ActorMethod, ActorSubclass, HttpAgent, Identity} from '@dfinity/agent';
import {IDL} from '@dfinity/candid';
import {Principal} from '@dfinity/principal';
import {EnvStore} from '../stores/env.store';

export const createActor = async <T = Record<string, ActorMethod>>({
  canisterId,
  idlFactory,
  identity
}: {
  canisterId: string | Principal;
  idlFactory: IDL.InterfaceFactory;
  identity: Identity;
}): Promise<ActorSubclass<T>> => {
  const host: string = EnvStore.getInstance().localIdentity()
    ? 'http://localhost:8000/'
    : 'https://ic0.app';

  const agent: HttpAgent = new HttpAgent({identity, ...(host && {host})});

  if (EnvStore.getInstance().localIdentity()) {
    // Fetch root key for certificate validation during development
    await agent.fetchRootKey();
  }

  // Creates an actor with using the candid interface and the HttpAgent
  return Actor.createActor(idlFactory, {
    agent,
    canisterId
  });
};

```

Merry Xmas 🎄

---

<div class="post-metadata">

**Author:** ![HinzaAsif](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/hinzaasif/32/18076_2.png) [@HinzaAsif](https://forum.dfinity.org/u/HinzaAsif)\
**Post date:** [February 17, 2024, 4:51am UTC](https://forum.dfinity.org/t/how-to-use-next-js-on-the-frontend/17545/15 "2024-02-17T04:51:16Z")

</div>

Hello everyone, this is Hinza here, CEO of [NFTStudio24.com](http://NFTStudio24.com). I want to share my experience with the ICP framework. There is no doubt that the Internet Computer has great technology, and this blockchain has a strong and bright future.

Our website, NFTStudio24, is the first decentralized news media platform in Japan. As you know, it’s very important for news media platforms to have ranked keywords on Google search and other search engines. For that, Google should index your app or website correctly.

We are facing this issue. Here is all the information; please help us if you know of any solution.

ISR in Next.js Static Export\*\*

ISR, or Incremental Static Regeneration, is a feature in Next.js that allows you to update static content incrementally without rebuilding the entire application. However, ISR relies on server-side rendering (SSR) or serverless functions to generate dynamic content at runtime, which is then cached and served statically for subsequent requests.

When you perform a static export in Next.js _(Which is the only way we can use nextjs in an assets canister)_, the application is pre-rendered at build time, and all pages are generated as static HTML files. This means that there is no server running to handle requests and execute ISR logic at runtime.

**Challenges with Implementing ISR in Static Export:**

1. **No Server Runtime:** In a static export, there’s no server runtime available to execute ISR logic. ISR relies on the server to regenerate static content dynamically when requested.

2. **Pre-generated Static Content:** During static export, all pages are pre-rendered into static HTML files. These files are served directly by a static file server like Nginx or CDN, without any backend logic execution.

3. **Limited Dynamic Behavior:** ISR is inherently designed for dynamic content generation. While it’s possible to include dynamic data in static exports using methods like getStaticProps or getServerSideProps, these are executed only during the build process and cannot be triggered dynamically at runtime.

4. **Build-time vs. Runtime:** ISR operates at runtime, while static exports are generated at build time. They serve different purposes and have different mechanisms for handling dynamic content.
