iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🙆‍♀️

Building a Full-Stack Web Application with Hono on AWS Amplify Hosting

に公開

AWS Amplify Hosting provides native support for SSR in frameworks like Next.js and Nuxt.js, and the operational specifications for this feature (Compute) are publicly available.

https://docs.aws.amazon.com/amplify/latest/userguide/ssr-deployment-specification.html

By leveraging this, you can deploy an API server built with Node.js and Hono to create a full-stack web application.

Below is an example of a minimal setup containing only the necessary files.

├── amplify.yml
└── app
    ├── compute
    │   └── default
    │       ├── index.js
    │       ├── node_modules
    │       ├── package-lock.json
    │       └── package.json
    ├── deploy-manifest.json
    └── static
        ├── index.html
        └── styles.css

*In actual development, it is ideal for the contents of the app/ directory to be the result of bundling with a build tool. This irregular configuration is used here for explanatory purposes.

amplify.yml

amplify.yml is the build configuration file for Amplify. When you perform a git push, the build is executed in the AWS environment according to these settings.

version: 1
frontend:
    phases:
        build:
            commands:
                - 'cd app/compute/default/ && npm install'
    artifacts:
        baseDirectory: app
        files:
            - '**/*'
    cache:
        paths:
            - '.npm/**/*'

The command 'cd app/compute/default/ && npm install' is executed because node_modules needs to be placed within the directory targeted for upload.

deploy-manifest.json

This is the most important file. The deploy-manifest.json contains settings for how to arrange resources in the AWS build environment.

deploy-manifest.json
{
  "version": 1,
  "framework": { "name": "hono", "version": "4.6.3" },
  "routes": [
    {
      "path": "/api/*",
      "target": {
        "kind": "Compute",
        "src": "default"
      }
    },
    {
      "path": "/*",
      "target": {
        "kind": "Static"
      }
    }
  ],
  "computeResources": [
    {
      "name": "default",
      "runtime": "nodejs20.x",
      "entrypoint": "index.js"
    }
  ]
}

In the above, requests to /api/* are routed to the API executed by app/compute/default/index.js.

Other requests will return the static files under app/static. These are delivered as static files via CloudFront. In this case, we have placed index.html and styles.css here.

(Of course, it is also possible to direct all page-level requests to the Node.js server running Hono and return HTML there to build the interface as an MPA.)

app/compute/default/

This is the starting directory for Compute resources. Everything under this directory is deployed to AWS Lambda (or Lambda@Edge). Since these Lambda functions are managed by AWS, they cannot be edited directly by the user.

index.js
const { Hono } = require('hono');
const { serve } = require('@hono/node-server');

const api = new Hono().basePath('/api');

// In-memory storage for the TODO app
const todos = [];

// Fetch TODOs
api.get('/todos', (c) => c.json(todos));

// Add a TODO
api.post('/todos', async (c) => {
  const { title } = await c.req.json();
  const newTodo = { id: todos.length + 1, title, completed: false };
  todos.push(newTodo);
  return c.json(newTodo, 201);
});

// Update a TODO
api.put('/todos/:id', async (c) => {
  const id = parseInt(c.req.param('id'));
  const { title, completed } = await c.req.json();
  const todo = todos.find(t => t.id === id);
  if (!todo) {
    return c.json({ error: 'Todo not found' }, 404);
  }
  todo.title = title || todo.title;
  todo.completed = completed !== undefined ? completed : todo.completed;
  return c.json(todo);
});

// Delete a TODO
api.delete('/todos/:id', (c) => {
  const id = parseInt(c.req.param('id'));
  const index = todos.findIndex(t => t.id === id);
  if (index === -1) {
    return c.json({ error: 'Todo not found' }, 404);
  }
  todos.splice(index, 1);
  return c.json({ message: 'Todo deleted successfully' });
});

const port = 3000
console.log(`Server is running on port ${port}`)

serve({
  fetch: api.fetch,
  port
})

This is a straightforward Hono API server. I used an in-memory array to store data to demonstrate maintaining state on the server side.

app/static/

This is the directory for static files. I created a simple UI with index.html and styles.css to interact with the API mentioned above.

(Source code omitted)

Deployment

Once you push to the repository configured in the Amplify console, Amplify will automatically start the deployment.

You can view the web application actually deployed through these steps at the following URL:

https://main.d34bg7pb0ejo8j.amplifyapp.com/

The UI doesn't have much to see, so please use the developer console to check the API communication and verify that the entered data is being maintained on the server side.

Advanced Topics

The fact that static/index.html can be hosted means you can build an SPA from here. You can build an SPA using Vite + React to create an application that transitions between multiple screens.

Additionally, you can integrate SDKs for related Amplify services into the server-side API portion, allowing for a design that isolates dependencies strictly to the server side.

Furthermore, baseDirectory should ideally not be included in the git repository; instead, the results generated and bundled during the build process should be placed there. This would allow for the use of TypeScript.

One point to note is that the compute/default subdirectory cannot exceed 220 MB after compression.

References

https://docs.aws.amazon.com/amplify/latest/userguide/deploy-express-server.html

https://zenn.dev/laiso/articles/1e859a5a728202

https://zenn.dev/laiso/articles/c7eba95ce43feb

https://zenn.dev/laiso/articles/8c619c38bd7b7b

Discussion