72 | )
73 | }
74 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Next.js Internet Computer Starter Template
2 |
3 | This project provides a simple starter template for Dfinity Internet Computer using Next.js framework as frontend.
4 |
5 | **The Most Recent Updates**
6 |
7 | - NextJS 15.2.0
8 | - DFX 0.25.0
9 | - NodeJS 22.12.0
10 |
11 | **Backend**
12 |
13 | - A simple greeting hello world canister written in Motoko
14 | - ImageBucket canister written in Motoko with create image, delete image and getImageById
15 |
16 | **Frontend**
17 |
18 | - A simple React HTML form with name input, sending it to greet canister and showing the returned result
19 | - An Image Upload HTML form with Pick an Image button, upload the image to image canister, loading the image back from the canister and display it using useImageObject React Hook
20 |
21 | ## Live Demo in IC Mainnet 🥳
22 |
23 | https://u4gun-5aaaa-aaaah-qabma-cai.raw.ic0.app
24 |
25 | 
26 |
27 | ## Quick Start (Run locally)
28 |
29 | Install:
30 |
31 | - NodeJS 18.\* or higher https://nodejs.org/en/download/
32 | - Internet Computer dfx CLI https://internetcomputer.org/docs/current/developer-docs/setup/install/
33 | - Visual Studio Code (Recommended Code Editor) https://code.visualstudio.com/Download
34 | - VSCode extension - Motoko (Recommended) https://marketplace.visualstudio.com/items?itemName=dfinity-foundation.vscode-motoko
35 |
36 | ```bash
37 | sh -ci "$(curl -fsSL https://internetcomputer.org/install.sh)"
38 | ```
39 |
40 | Clone this Git repository:
41 |
42 | ```bash
43 | git clone https://github.com/dappblock/nextjs-ic-starter
44 | ```
45 |
46 | Open command terminal:
47 | Enter the commands to start dfx local server in background:
48 |
49 | ```bash
50 | cd nextjs-ic-starter
51 | dfx start --background
52 | ```
53 |
54 | Note: If you run it in MacOS, you may be asked to allow connections from dfx local server.
55 |
56 | Enter the commands to install dependencies, deploy canister and run Next.js dev server:
57 |
58 | ```bash
59 | npm install
60 | dfx deploy --network local
61 | npm run dev
62 | ```
63 |
64 | http://localhost:3000/
65 |
66 | Cleanup - stop dfx server running in background:
67 |
68 | ```bash
69 | dfx stop
70 | ```
71 |
72 | ## Project Structure
73 |
74 | Internet Computer has the concept of [Canister](https://smartcontracts.org/docs/current/concepts/canisters-code/) which is a computation unit. This project has 3 canisters:
75 |
76 | - hello (backend)
77 | - image (backend)
78 | - hello_assets (frontend)
79 |
80 | Canister configurations are stored in dfx.json.
81 |
82 | ### Backend
83 |
84 | Backend code is inside /backend/ written in [Motoko language](https://internetcomputer.org/docs/current/motoko/main/motoko-introduction). Motoko is a type-safe language with modern language features like async/await and actor build-in. It also has [Orthogonal persistence](https://internetcomputer.org/docs/current/motoko/main/motoko/#orthogonal-persistence) which I find very interesting.
85 |
86 | Image canister is introduced from release v0.2.0. It makes use of orthogonal persistence through stable variables and provides functions for create, delete and get image. See /backend/service/Image.mo.
87 |
88 | ### Frontend
89 |
90 | Frontend code follows Next.js folder convention with /pages storing page React code, /public storing static files including images. This project uses CSS modules for styling which is stored in /ui/styles. React Components are stored in /ui/components
91 |
92 | Entry page code is inside /pages/index.js where the magic starts. With the DFX UI declarations generated code, frontend can use RPC style call to server side actor and its functions without worrying about HTTP request and response parsing.
93 |
94 | To generate UI declarations:
95 |
96 | ```
97 | dfx generate
98 | ```
99 |
100 | It will generate files in src/declarations for each canister. In our case, it is image, hello and hello_assets but we only need the backend canister image and hello UI declarations here.
101 |
102 | The next step is to adapt it to work with Next.js.
103 | The final adapted code is in ui/declaration/hello/index.js.
104 | You can also follow the steps below to update it.
105 |
106 | Basically, copy image.did.js and index.js from src/declarations/image/
107 |
108 | ```
109 | cp src/declarations/image/image.did.js ui/declarations/image/image.did.js
110 | cp src/declarations/image/index.js ui/declarations/image/index.js
111 | ```
112 |
113 | Repeat the same for hello.
114 |
115 | ```
116 | cp src/declarations/hello/hello.did.js ui/declarations/hello/hello.did.js
117 | cp src/declarations/hello/index.js ui/declarations/hello/index.js
118 | ```
119 |
120 | The next step is to update the canister ID env variable in each canister index.js to use NEXT_PUBLIC prefix so that NextJS can recognize when compiling it.
121 |
122 | Open ui/declarations/hello/index.js and look for the line:
123 |
124 | ```
125 | export const canisterId = process.env.HELLO_CANISTER_ID;
126 | ```
127 |
128 | Update HELLO_CANISTER_ID to NEXT_PUBLIC_HELLO_CANISTER_ID:
129 |
130 | ```
131 | export const canisterId = process.env.NEXT_PUBLIC_HELLO_CANISTER_ID
132 | ```
133 |
134 | To see the final code, check the original ui/declarations in the Git repo.
135 |
136 | The generated UI declarations also support TypeScript if you prefer TypeScript.
137 |
138 | We use a service locator pattern through actor-locator.js that will handle the dfx agent host using env var NEXT_PUBLIC_IC_HOST.
139 |
140 | Creating hello actor:
141 |
142 | ```javascript
143 | import { makeHelloActor } from "../ui/service/actor-adapter"
144 | const hello = makeHelloActor()
145 | ```
146 |
147 | Calling hello actor:
148 |
149 | ```javascript
150 | const greeting = await hello.greet(name)
151 | ```
152 |
153 | The beautiful part is you can invoke the hello actor greet function with async/await style as if they are on the same platform. For details, see React Components GreetingSection.js and ImageSection.js in /ui/components/.
154 |
155 | Webpack configuration:
156 | In Next.js, it's located in next.config.js.
157 |
158 | ## React Hook
159 |
160 | By using React Hook with actor UI declaration, it can greatly simplify frontend dev. It encourages component based composable logic. A great example is useImageObject.js React Hook in /ui/hooks. Given an imageId, useImageObject can load the image binary and convert it to a HTML image source object ready for use in .
161 |
162 | If you look closer, useImageObject.js depends on image-serivce.js which depends on actor-locator.js. When you open ImageSection.js, you can find how useImageObject is being used to greatly reduce the complexity and the underlying calls with Canister. This is the pattern I used very often in my Content Fly Dapp project.
163 |
164 | ## Backend dev
165 |
166 | After marking changes in backend code e.g main.mo in /backend/service/hello, you can deploy it to the local DFX server using:
167 |
168 | ```bash
169 | dfx deploy hello
170 | ```
171 |
172 | **hello** is the backend canister name defined in dfx.json.
173 |
174 | ## Frontend dev - Next.js Static Code
175 |
176 | Next.js developers are familiar with the handy hot code deployed in the Next.js dev environment when making changes in frontend code.
177 |
178 | After deploying your backend code as shown above, you can run Next.js local dev server **npm run dev** and edit your frontend code with all the benefits of hot code deploy.
179 |
180 | One thing to note is we use Next.js static code export here for hosting in Internet Computer so we can't use any features of Next.js that require server side NodeJS. Potentially, there might be ways to use Internet Computer canister as backend while deploying Next.js dapp to a hosting like Vercel that supports NodeJS server in the future. Further research is needed on that aspect. However, if you do want to run everything decentralized on blockchain including the frontend, you would want to deploy the exported static code to Internet Computer as well.
181 |
182 | ## Deploy and run frontend in local DFX server
183 |
184 | In order to simulate the whole Internet Computer experience, you can deploy and run frontend code to local DFX server by running:
185 |
186 | ```bash
187 | dfx start --background
188 | npm run build
189 | dfx deploy hello_assets
190 | ```
191 |
192 | **hello_assets** is the frontend canister defined in dfx.json.
193 |
194 | **npm run build** builds and export Next.js as static code storing in **/out** folder which would be picked up by **dfx deploy hello_assets** as defined in dfx.json with **/out** as the source.
195 |
196 | When it completes, you can open Chrome and browse to:
197 | http://localhost:8000/?canisterId=[canisterId]
198 |
199 | Replace [canisterId] with the hello_assets canister ID which you can find by running:
200 |
201 | ```bash
202 | dfx canister id hello_assets
203 | ```
204 |
205 | ## Environment Configuration
206 |
207 | There are three key configs following Next.js [Environment Variables](https://nextjs.org/docs/basic-features/environment-variables) configuration:
208 |
209 | **.env.development** stores configs for use in local dev.
210 |
211 | ```
212 | NEXT_PUBLIC_IC_HOST=http://localhost:8000
213 | ```
214 |
215 | **.env.production** is used when building and exporting static code using **npm run build**
216 |
217 | ```
218 | NEXT_PUBLIC_IC_HOST=http://localhost:8000
219 | ```
220 |
221 | Notice both files are identical if we want the Next.js dapp to interact with the local dfx server.
222 |
223 | Note **NEXT_PUBLIC** is the prefix used by Next.js to make env vars available to client side code through [build time inlining](https://nextjs.org/docs/basic-features/environment-variables).
224 |
225 | **.env.icprod** is included for deployment to Internet Computer ic network which would be covered below.
226 |
227 | ## Deploy to IC Network Canister
228 |
229 | The most exciting part is to deploy your Next.js / Internet Computer Dapp to production Internet Computer mainnet blockchain network.
230 |
231 | To do that you will need:
232 |
233 | - ICP tokens and convert it to [cycles](https://internetcomputer.org/docs/current/concepts/tokens-cycles/)
234 | - Cycles wallet
235 |
236 | Follow the [Network Deployment](https://internetcomputer.org/docs/current/developer-docs/setup/cycles/cycles-wallet/) guide to create a wallet.
237 | Dfinity offers [free cycle](https://faucet.dfinity.org/) to developers.
238 |
239 | Now, you can deploy your Next.js Dapp to Internet Computer IC network by adding **--network ic** to the dfx subcommand. We will first update our env var to point to IC network host. Then deploy the backend canister first, export Next.js static code and deploy frontend canister **hello_assets**.
240 |
241 | ```bash
242 | cp .env.icprod .env.production
243 | dfx deploy --network ic
244 | ```
245 |
246 | Open Chrome and go to https://[canisterId].raw.ic0.app/
247 | Replace [canisterId] by the hello_assets canister id in the IC network. You can find it by running:
248 |
249 | ```bash
250 | dfx canister --network ic id hello_assets
251 | ```
252 |
253 | Congratulations !! Well Done !! 👏 🚀 🎉
254 |
255 | ## Troubleshooting
256 |
257 | Use Chrome Dev Tools / Console / Network. Check if the dapp uses the right canister id and hostname.
258 |
259 | ## Author
260 |
261 | Henry Chan, henry@contentfly.app
262 | Twitter: @kinwo
263 |
264 | ## Contributing
265 |
266 | Please feel free to raise an issue or submit a pull request.
267 |
268 | ## License
269 |
270 | MIT
271 |
--------------------------------------------------------------------------------