---
title: "Implemente Next.js en AWS Amplify"
description: "Cómo implementar sus sitios web Next.js Server-Side Rendered (SSR) en AWS Amplify."
source: "https://www.launchfa.st/es/blog/deploy-nextjs-aws-amplify"
author: "Rishi Raj Jain"
created_at: 2024-03-31T00:00:00.000Z
---

> **Site index for agents**
> Fetch https://www.launchfa.st/llms.txt to discover every page on this site.
> Every page is also available as Markdown by appending `.md` to its URL.

<img width="1600" height="900" alt="Deploy Next.js to AWS Amplify" decoding="async" loading="eager" class="mt-4 border rounded-sm bg-cover bg-center bg-no-repeat transform will-change-auto" src="https://ik.imagekit.io/vjeqenuhn/launchfast-website/nextjs-amplify" />

En esta guía, aprenderá cómo implementar un proyecto Nextjs SSR en AWS Amplify. Pasará por el proceso de configuración de un nuevo proyecto Nextjs, habilitará la representación del lado del servidor mediante el adaptador AWS Amplify y, finalmente, lo implementará en AWS Amplify.

## Requisitos previos

Necesitará lo siguiente:

- [Nodejs 18](https://nodejs.org/en/blog/announcements/v20-release-announce) o posterior
- Una cuenta [AWS](https://aws.amazon.com/free)

## Crea una nueva aplicación Nextjs

Comencemos creando un nuevo proyecto Nextjs. Abra su terminal y ejecute el siguiente comando:

```bash
npx create-next-app@latest my-app
```

Cuando se le solicite, elija:

- `Sí` cuando se le solicite usar TypeScript
- `No` cuando se le solicita usar ESLint
- `Sí` cuando se le solicite usar Tailwind CSS
- `No` cuando se le solicita usar el directorio `src/`
- `Sí` cuando se le solicite usar App Router
- `No` cuando se le solicite personalizar el alias de importación predeterminado (`@/*`)

Una vez hecho esto, vaya al directorio del proyecto e inicie la aplicación en modo de desarrollo ejecutando el siguiente comando:

```bash
cd my-app
npm run dev
```

La aplicación debería ejecutarse en [localhost:3000](http://localhost:3000/)

Luego, deberá realizar el siguiente cambio en su archivo `nextconfigjs`. Abra el archivo y agregue el siguiente código:

```tsx
module.exports = {
    output: 'standalone', // [!code ++]
}
```

Luego, cree un archivo `amplifymjs` en la raíz del repositorio con el siguiente código:

```tsx
// File: amplify.mjs

import { join } from 'node:path';
import { writeFileSync, mkdirSync, existsSync, cpSync, rmSync } from 'node:fs';

// Define all the Amplify related directories
const amplifyDirectories = [
    join(process.cwd(), '.amplify-hosting'),
    join(process.cwd(), '.amplify-hosting', 'static'),
    join(process.cwd(), '.amplify-hosting', 'static', '_next'),
    join(process.cwd(), '.amplify-hosting', 'compute'),
    join(process.cwd(), '.amplify-hosting', 'compute', 'default'),
    join(process.cwd(), '.amplify-hosting', 'compute', 'default', 'node_modules'),
]

// Create directories if they do no exist already
if (existsSync(amplifyDirectories[0])) rmSync(amplifyDirectories[0], { force: true, recursive: true })

// Create directories if they do no exist already
amplifyDirectories.forEach((i => mkdirSync(i)))

// A general default configuration to fallback to compute if no matching static assets found
const deployManifestConfig = {
    version: 1,
    routes: [
        {
            path: `/assets/*`,
            target: {
                kind: "Static",
            },
        },
        {
            path: `/*.*`,
            target: {
                kind: "Static",
            },
            fallback: {
                kind: "Compute",
                src: "default",
            },
        },
        {
            path: "/*",
            target: {
                kind: "Compute",
                src: "default",
            },
        },
    ],
    computeResources: [
        {
            name: "default",
            entrypoint: "server.js",
            runtime: "nodejs18.x",
        },
    ],
    framework: {
        name: "next",
        version: "13.5.6",
    },
};

// Write the config to .amplify-hosting/deploy-manifest.json
writeFileSync(
    join(process.cwd(), ".amplify-hosting", "deploy-manifest.json"),
    JSON.stringify(deployManifestConfig),
);

// Copy the static assets generated in .next/static and public to .amplify-hosting/static directory
cpSync(join(process.cwd(), 'public'), amplifyDirectories[1], { recursive: true })
cpSync(join(process.cwd(), '.next', 'static'), amplifyDirectories[2], { recursive: true })

// Copy the static assets generated in .next/standalone to .amplify-hosting/compute directory
cpSync(join(process.cwd(), '.next', 'standalone'), amplifyDirectories[4], { recursive: true })

// Remove .next/static and public from .amplify-hosting/compute/default
rmSync(join(amplifyDirectories[4], '.next', 'static'), { force: true, recursive: true })
rmSync(join(amplifyDirectories[4], 'public'), { force: true, recursive: true })
```

Luego, cree un archivo `amplifyyml` en la raíz del repositorio con el siguiente código:

```yml
version: 1
frontend:
  phases:
    preBuild:
      commands:
        - npm ci
    build:
      commands:
        - env >> .env
        - npm run build
        - node amplify.mjs
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*
```

El código anterior hace lo siguiente:

- Utiliza comandos `preBuild` para instalar las dependencias de su proyecto Nextjs
- Utiliza comandos `build` para:
  - Almacene todas las variables de entorno en el archivo `env` en la raíz del proyecto
  - Construya su aplicación Nextjs
  - Mueva el directorio `node_modules` y el archivo `env` al directorio de cálculo de Amplify

## Implementar en AWS Amplify

El código ahora está listo para implementarse en AWS Amplify. Utilice los siguientes pasos para implementarlo:

- Comience creando un repositorio de GitHub que contenga el código de su aplicación.

- Luego, navegue hasta el panel de AWS Amplify y haga clic en **Comenzar** en la sección **Alojar su aplicación web**

<img width="3024" height="1642" alt="Host your web app in AWS Amplify" decoding="async" loading="lazy" class="mt-4 border rounded-sm bg-cover bg-center bg-no-repeat transform will-change-auto" src="https://ik.imagekit.io/vjeqenuhn/launchfast-website/astro-aws-amplify/317524135-edf84da6-6546-49b9-a770-a0ea11d5584d.png" />

- Selecciona **GitHub** como fuente de tu repositorio Git.

<img width="2415" height="1354" alt="GitHub as code source in AWS Amplify" decoding="async" loading="lazy" class="mt-4 border rounded-sm bg-cover bg-center bg-no-repeat transform will-change-auto" src="https://ik.imagekit.io/vjeqenuhn/launchfast-website/astro-aws-amplify/317524200-8058e41b-858b-4907-85fd-fcee8f581b92-1.png" />

- Vincula el nuevo proyecto al repositorio de GitHub que acabas de crear.

<img width="2442" height="1492" alt="Link Repo in AWS Amplify" decoding="async" loading="lazy" class="mt-4 border rounded-sm bg-cover bg-center bg-no-repeat transform will-change-auto" src="https://ik.imagekit.io/vjeqenuhn/launchfast-website/astro-aws-amplify/screenshot-2024-03-29-at-2-12-15-am.png" />

- Asigne un nombre a su proyecto y haga clic en **Configuración avanzada**

<img width="3024" height="1240" alt="Name the project in AWS Amplify" decoding="async" loading="lazy" class="mt-4 border rounded-sm bg-cover bg-center bg-no-repeat transform will-change-auto" src="https://ik.imagekit.io/vjeqenuhn/launchfast-website/astro-aws-amplify/317524364-1c5ce259-5e64-49ab-8937-79fb8df0abee-1.png" />

- En **Configuración avanzada**, actualice las **Variables de entorno** para que coincidan con las de su archivo `env` local y `PORT` como 3000. Haga clic en **Siguiente** para continuar.

<img width="2881" height="1340" alt="Add Environment Variables in AWS Amplify" decoding="async" loading="lazy" class="mt-4 border rounded-sm bg-cover bg-center bg-no-repeat transform will-change-auto" src="https://ik.imagekit.io/vjeqenuhn/launchfast-website/astro-aws-amplify/317524371-e48bbefd-4b43-4358-b0f0-09fb4c75c1f1-1.png" />

- Haga clic en **Guardar e implementar** para implementar su sitio web.

<img width="2940" height="1396" alt="Deploy to AWS Amplify" decoding="async" loading="lazy" class="mt-4 border rounded-sm bg-cover bg-center bg-no-repeat transform will-change-auto" src="https://ik.imagekit.io/vjeqenuhn/launchfast-website/astro-aws-amplify/screenshot-2024-03-29-at-2-19-26-am.png" />

- Obtenga la URL de implementación bajo el título **Dominio** en la información de compilación exitosa.

<img width="2881" height="1511" alt="Grab Deployment URL in AWS Amplify" decoding="async" loading="lazy" class="mt-4 border rounded-sm bg-cover bg-center bg-no-repeat transform will-change-auto" src="https://ik.imagekit.io/vjeqenuhn/launchfast-website/astro-aws-amplify/317524382-873195fb-542d-4cf1-b076-96d1cb501caa-1.png" />

## Conclusión

¡Hurra! Ahora tiene un proyecto Nextjs que se implementa automáticamente en AWS Amplify tras la inserción de Git.

Si tiene alguna pregunta o comentario, no dude en comunicarse conmigo en [Twitter](https://twitter.com/direct_messages/create/rishi_raj_jain_)
