diff --git a/src/content/docs/en/pages/devtools/azion-edge-runtime/nextjs/2023-02-14-index.mdx b/src/content/docs/en/pages/devtools/azion-edge-runtime/nextjs/2023-02-14-index.mdx index 8599b3009a..a20248630a 100644 --- a/src/content/docs/en/pages/devtools/azion-edge-runtime/nextjs/2023-02-14-index.mdx +++ b/src/content/docs/en/pages/devtools/azion-edge-runtime/nextjs/2023-02-14-index.mdx @@ -19,6 +19,93 @@ You can find more detailed examples in the [Azion Bundler repository](https://gi --- +## OpenNext + +The [`@aziontech/opennextjs-azion`](https://www.npmjs.com/package/@aziontech/opennextjs-azion) adapter lets you deploy Next.js apps to [Azion Functions](https://www.azion.com/en/products/edge-functions/) using the [Node.js "runtime" from Next.js](https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes). + +### Get Started + +##### New apps + +To create a new Next.js app, pre-configured to run on Azion using `@aziontech/opennextjs-azion`, run: + +```shell +npx create-next-app@14.2.4 my-next-app --use-npm && cd my-next-app && npm install @aziontech/opennextjs-azion@latest +``` + +##### Existing Next.js apps + +[Follow the guide here](/azion/get-started) to use [@aziontech/opennextjs-azion](https://www.npmjs.com/package/@aziontech/opennextjs-azion) with an existing Next.js app. + +### Supported Next.js versions + +All minor and patch versions of Next.js 15 and the latest minor of Next.js 14 are supported. + +To help improve compatibility, we encourage you to [report bugs](https://github.com/aziontech/opennextjs-azion/issues) and contribute code! + +### Supported Next.js features + +| Feature | Support | Comments | +|---|---|---| +| [App Router](https://nextjs.org/docs/app) | 🟢 | | +| [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) | 🟢 | | +| [Dynamic routes](https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes) | 🟢 | | +| [Static Site Generation (SSG)](https://nextjs.org/docs/app/building-your-application/rendering/server-components#static-rendering-default) | 🟢 | | +| [Server-Side Rendering (SSR)](https://nextjs.org/docs/app/building-your-application/rendering/server-components) | 🟢 | | +| [Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware) | 🟢 | | +| [Node Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware#runtime) | 🟡 | introduced in 15.2 are not yet supported | +| [Image Optimization](https://nextjs.org/docs/app/building-your-application/optimizing/images) | 🔴 | | +| [Partial Prerendering (PPR)](https://nextjs.org/docs/app/building-your-application/rendering/partial-prerendering) | 🟢 | | +| [Pages Router](https://nextjs.org/docs/pages) | 🟢 | | +| [Incremental Static Regeneration (ISR)](https://nextjs.org/docs/app/building-your-application/data-fetching/incremental-static-regeneration) | 🟢 | | +| [Support for after](https://nextjs.org/blog/next-15-rc#executing-code-after-a-response-with-nextafter-experimental) | 🟢 | | +| [Composable Caching](https://nextjs.org/blog/composable-caching) | 🔴 | ('use cache') | + +:::note +Azion Functions have a maximum size limit of 50 MB per function. After building your project, pay attention to the compressed (gzipped) size of your deployment package—only the compressed size counts toward this limit. +For more details, see the [documentation on Function size limits](/en/documentation/products/build/edge-application/edge-functions/#limits). +::: + +### Examples + +To create a new Next.js app for Azion, you can use the following starter projects and templates: + +#### Basic starter projects + +- [Next.js + TypeScript + Tailwind Template](https://github.com/aziontech/azion-samples/tree/dev/templates/opennextjs/nextal-next-typescript-tailwind) — a ready-to-use template for building modern Next.js apps on Azion Functions. +- [Node Playground (Next.js 13)](https://github.com/aziontech/bundler-examples/tree/main/examples/nextjs/node-playground-13) — an example showing how to run Next.js 13 in a Node.js environment on Azion. + +You can use these repositories to understand how to configure your Next.js app to run on Azion, or as a starting point for your own projects. + +### Known issues + +#### TS Config +- Your `tsconfig.json` must include the following setting: + +```json +"moduleResolution": "bundler" +``` + + If this is not set, you may encounter issues during the build or runtime process. + +- There is a known issue with ESM and the `open-next.config.ts` file. If you have an older project or one that depends on a specific TypeScript version or custom configuration, you may need to: + - Reconfigure your project (for example, by setting `moduleResolution: bundler` as above), **or** + - Add the following to your `tsconfig.json`: + +```json +"exclude": ["node_modules", "open-next.config.ts"] +``` + +Whether this works depends on your project setup. In some cases, excluding `open-next.config.ts` allows the build to proceed, but you may still encounter errors, especially if your project uses features like `_app.mdx` or other advanced configurations. This is particularly relevant for projects that haven't been tested with these setups, and issues may also occur in other environments (such as the Cloudflare package). + +#### Local Development + +- Some applications may use Node.js or Web Standard APIs that are not fully supported by Azion's local development environment. However, these features might be available in the actual Azion runtime. + +:::tip +If your application does not work as expected during local development, try deploying it to Azion before troubleshooting further, as it may work correctly in the deployed environment. +::: + ## Next.js 14.x.y | Feature | Support | Comments | @@ -37,7 +124,7 @@ You can find more detailed examples in the [Azion Bundler repository](https://gi | Static Pages | 🟢 | | | SSR | 🟢 | | | SSG | 🟢 | | -| Edge API Routes | 🟢 | | +| API Routes | 🟢 | | | Dynamic Routes | 🟢 | | | Middleware | 🟡 | Features: rewrite, redirect, continue to response, set request header, throw error, set response header, and set response cookie| | Next configs | 🟡 | Features: rewrite before files, rewrite after files, rewrite fallback, redirects, and header definition | @@ -50,7 +137,7 @@ You can find more detailed examples in the [Azion Bundler repository](https://gi | Static Pages | 🟢 | | SSR | 🟢 | | | SSG | 🟢 | | -| Edge API Routes | 🟢 | | +| API Routes | 🟢 | | | Dynamic Routes | 🟢 | | | Middleware | 🟡 | Features: rewrite, redirect, continue to response, set request header, throw error, return response, set response header, and set response cookie | | Next configs | 🟡 | Features: rewrite before files, rewrite after files, rewrite fallback, redirects, and header definition | diff --git a/src/content/docs/en/pages/guides/open-next/get-started-opennext.mdx b/src/content/docs/en/pages/guides/open-next/get-started-opennext.mdx new file mode 100644 index 0000000000..d04e2d0c74 --- /dev/null +++ b/src/content/docs/en/pages/guides/open-next/get-started-opennext.mdx @@ -0,0 +1,182 @@ +--- +title: Get Started With OpenNext +description: >- + Get started with OpenNext on Azion: create or adapt a Next.js app, configure caching and storage for ISR/SSG, develop locally with the Azion CLI, and deploy to production. +permalink: /documentation/products/guides/opennext/get-started/ +meta_tags: >- + Next.js compatibility, Azion Web Platform, SSR, SSG, Middleware Features, + Static Generation, Server-side Rendering, Next.js Routing, Next.js + Performance, Next.js Integrations +namespace: documentation_guides_opennext_get_started +--- + +The `@aziontech/opennextjs-azion` adapter lets you deploy Next.js apps to Azion Web Platform. This guide will help you set up a new or existing Next.js project for Azion, configure caching, develop locally, and deploy to production. + +--- + +### Prerequisites + +- [CLI Installed](/en/documentation/products/azion-cli/overview/#installing-azion-cli). + +--- + +#### Creating a New Next.js App + +To create a new Next.js app pre-configured for Azion: + +```sh +npx create-next-app@14.2.4 my-next-app --use-npm +cd my-next-app +npm install @aziontech/opennextjs-azion@latest +``` + +Or use a starter template: + +- [Next.js + TypeScript + Tailwind Template](https://github.com/aziontech/azion-samples/tree/dev/templates/opennextjs/nextal-next-typescript-tailwind) +- [Node Playground (Next.js 13)](https://github.com/aziontech/bundler-examples/tree/main/examples/nextjs/node-playground-13) + +--- + +#### Existing Next.js Apps + +1. Install the Azion Adapter: + +```sh +npm install @aziontech/opennextjs-azion@latest +``` + +2. Configure `open-next.config.ts`: + +Create or update `open-next.config.ts` in your project root. Example: + +```ts +import { defineAzionConfig } from "@aziontech/opennextjs-azion"; + +export default defineAzionConfig({ + // See /azion/caching for advanced options +}); +``` + +3. Update `tsconfig.json`: + +:::warning +Your `tsconfig.json` must include: ```json "moduleResolution": "bundler" ```. This is required for correct build and runtime behavior. +::: + +If you encounter issues with ESM or `open-next.config.ts`, you may need to add: + +```json +"exclude": ["node_modules", "open-next.config.ts"] +``` + +See [Known Issues](/en/documentation/devtools/azion-edge-runtime/compatibility/nextjs/#known-issues) for more details. + +1. Azion CLI Build and Deploy: + +- `azion build`: Builds your app for Azion. +- `azion preview`: Runs a local preview using Azion CLI. +- `azion deploy`: Deploys to Azion Web Platform using Remote Deployment. + - or `azion deploy --local` to deploy to Azion Web Platform using Local Deployment. + +5. Set Up Caching and Storage: + +Example Azion config: + +```ts +AzionCache +Type definition for the cache configuration. +``` + +Properties: + +| Property | Type | Description | +| --- | --- | --- | +| name | string | Name of the cache configuration. | +| stale? | boolean | Whether to allow stale content. | +| queryStringSort? | boolean | Whether to sort query string parameters. | +| methods? | CacheMethods | HTTP methods to cache. | +| post? | boolean | Whether to cache POST requests. | +| options? | boolean | Whether to cache OPTIONS requests. | +| browser? | BrowserCacheConfig | Browser cache settings. | +| browser.maxAgeSeconds | number \| string | Maximum age for browser cache in seconds. | +| edge? | EdgeCacheConfig | Cache settings. | +| edge.maxAgeSeconds | number \| string | Maximum age for cache in seconds. | +| cacheByCookie? | CacheByCookieConfig | Cache by cookie settings. | +| cacheByCookie.option | 'ignore' \| 'varies' \| 'whitelist' \| 'blacklist' | Cache by cookie option. | +| cacheByCookie.list? | string[] | List of cookies to use for caching. | +| cacheByQueryString? | CacheByQueryStringConfig | Cache by query string settings. | +| cacheByQueryString.option | 'ignore' \| 'varies' \| 'whitelist' \| 'blacklist' | Cache by query string option. | +| cacheByQueryString.list? | string[] | List of query string parameters to use for caching. | + + +```js +// azion.config.cjs +module.exports = { + build: { preset: "opennextjs", polyfills: true }, + origin: [{ name: "origin-storage-default", type: "object_storage" }], + functions: [{ name: "handler", path: ".edge/worker.js" }], + cache: [ + { + name: 'Default Cache', + browser: { maxAgeSeconds: 3600 }, + edge: { maxAgeSeconds: 7200 }, + }, + ], + rules: { + request: [ + { + name: "Set storage origin for _next/static", + match: "^/_next/static/", + behavior: { setOrigin: { name: "origin-storage-default", type: "object_storage" }, deliver: true }, + }, + { + name: "Deliver Static Assets", + match: ".(css|js|ttf|woff|woff2|pdf|svg|jpg|jpeg|gif|bmp|png|ico|mp4|json)$", + behavior: { setOrigin: { name: "origin-storage-default", type: "object_storage" }, deliver: true }, + }, + { + name: "Execute Function", + match: "^/", + behavior: { runFunction: "handler", forwardCookies: true }, + }, + ], + }, +}; +``` + +--- + +### Local Development + +Use the [Azion CLI](/en/documentation/products/cli/) for local development: + +```sh +azion dev +``` + +This runs your Application locally, simulating the Azion platform. [See Troubleshooting](/en/documentation/products/guides/opennext/troubleshooting/) for tips on debugging and log monitoring. + +--- + +### Deployment + +Deploy your app to Azion Web Platform: + +```sh +azion deploy +``` + +Or use the Azion CLI to deploy to Azion Web Platform using local deployment: + +```sh +azion deploy --local +``` + +--- + +### Best Practices & Troubleshooting + +- See [Known Issues](/en/documentation/devtools/azion-edge-runtime/compatibility/nextjs/#known-issues) for important config notes. +- See [Troubleshooting](/en/documentation/products/guides/opennext/troubleshooting/) for local dev, logging, and debugging tips. +- Explore [Examples](/en/documentation/devtools/azion-edge-runtime/compatibility/nextjs/#examples) for starter projects and templates. +- For advanced caching, see [Caching](/azion/caching). diff --git a/src/content/docs/en/pages/guides/open-next/troubleshooting-opennext.mdx b/src/content/docs/en/pages/guides/open-next/troubleshooting-opennext.mdx new file mode 100644 index 0000000000..e22052edad --- /dev/null +++ b/src/content/docs/en/pages/guides/open-next/troubleshooting-opennext.mdx @@ -0,0 +1,161 @@ +--- +title: Troubleshooting an OpenNext Application +description: >- + Learn how to troubleshoot OpenNext apps on Azion: run locally with Azion CLI, tail logs, use Real‑Time Events, Metadata & GraphQL APIs, fix size limits and environment variables. +permalink: /documentation/products/guides/opennext/troubleshooting/ +meta_tags: >- + Next.js compatibility, Azion Web Platform, SSR, SSG, Middleware Features, + Static Generation, Server-side Rendering, Next.js Routing, Next.js + Performance, Next.js Integrations +namespace: documentation_guides_opennext_troubleshooting +--- + +## 1. Local Development and Debugging with the Azion CLI + +The first and most crucial troubleshooting step is performed even before deployment. The Azion CLI allows you to run your function in a local environment that simulates the Azion platform. + +**Key Command**: +```bash +azion dev +``` +When you run this command in the root of your project, the CLI starts a local server. Any request made to this server will execute your function, and outputs from `console.log`, as well as any errors, will be displayed directly in your terminal. + +**Benefits**: +* **Immediate Feedback**: See the results of your code changes instantly. +* **Time Savings**: Avoids the need to deploy for every minor change. +* **Controlled Environment**: Debug your application's logic without affecting the production environment. + +**Example**: + +```javascript +// main.js +export default function myWorker(event) { + console.log("Function executed successfully!"); + return new Response('Hello World'); +} +``` + +After running `azion dev` and accessing the local server, your terminal will display: + +``` +Function executed successfully! +``` + +## 2. Monitoring Logs in Production + +Once your application is in production, you need tools to observe its behavior in real time and analyze past events. + +### Real-Time Access (Tailing) + +To monitor logs as they happen, use the `--tail` argument with the Azion CLI. This creates a continuous session that displays new logs as they are generated. + +**Key Command**: + +```bash +azion logs cells --tail +``` + +This command is ideal for debugging issues that are currently happening or for monitoring the application's behavior during a new deployment. + +### Viewing via the Azion Console (Real-Time Events) + +For a more visual analysis with more filtering options, the Azion Console is the ideal tool. + +1. Access the **Real-Time Manager**. +2. In the menu, go to **Observe > Real-Time Events**. +3. Select the **Functions** Console tab. + +On this screen, you can: +* View all logs generated by `console.log` in your functions. +* Filter events by time periods (last 15 minutes, last hour, custom range). +* Search for specific log messages. +* Analyze detailed information for each event, such as `Function ID` and `Timestamp`. + +## 3. Advanced Analysis with the Metadata API + +Often, the problem lies not just in the code, but in the context of the request (origin, headers, etc.). The Azion **Metadata API** allows your functions to access this data. You can log this metadata to better understand your application's behavior. + +**Practical Example**: + +Imagine you want to check which continent a request is coming from. + +```javascript +// main.js +export default function myWorker(event) { + const request = event.request; + const continentCode = request.metadata['geoip_continent_code']; + + console.log(`Request received from continent: ${continentCode}`); + + // Additional logic based on the continent... + + return new Response(`Hello, ${continentCode}!`); +} +``` + +By deploying this code and monitoring the logs with `azion logs cells --tail`, you will see messages like: + +``` +Request received from continent: SA + +``` + +This allows you to debug routing logic, security (for example, blocking by region), and content personalization. + +## 4. Structured Log Collection with the GraphQL API + +For automation, integration with external monitoring systems (like Datadog or New Relic), or for performing complex analyses, Azion provides a **GraphQL API**. + +With it, you can execute queries to fetch logs in a structured format. + +**Key Tool**: The **GraphQL Playground**, available in the Azion Console, allows you to build and test your queries before integrating them into your tools. + +**Example Query**: +This query fetches the 10 most recent Console events containing a specific log line. + +```graphql +query getConsoleEvents { + cellsConsoleEvents( + limit: 10, + filter: { + tsRange: {begin: "2024-09-28T12:00:00", end: "2024-09-28T13:00:00"}, + line: {contains: "Function failed"} + }, + orderBy: [ts_ASC] + ) { + ts + configurationId + functionId + line + } +} +``` + +## 5. Function size exceeds limit + +Azion imposes limits on the size of functions, the default limit is 20MB. If your deployment fails with an error about function size, it usually means your bundled code is too large for the platform. + +To resolve this: + +1. **Analyze your bundle**: Use tools like [Webpack Bundle Analyzer](https://www.npmjs.com/package/webpack-bundle-analyzer) or [ESBuild Analyzer](https://esbuild.github.io/analyze/) to identify large dependencies. +2. **Remove unused dependencies**: Audit your `package.json` and codebase for unnecessary packages. +3. **Optimize imports**: Prefer importing specific functions instead of entire libraries (for example, `import { parse } from "date-fns"` instead of `import * as dateFns from "date-fns"`). +4. **Leverage Azion’s caching**: Move static assets and large files to Azion’s Object Storage or CDN, and reference them via URLs instead of bundling them. + +Refer to [Azion’s documentation on Functions limits](/en/documentation/products/build/edge-application/edge-functions/#limits) for up-to-date size restrictions. + +--- + +## 6. My environment variables are not available in the Functions + +Azion allows you to define environment variables for your functions, but they must be configured explicitly in the Azion Console or via the API. + +If your code can't access an expected environment variable: + +1. **Check the Azion Console**: Go to your Application > Functions > Environment Variables and ensure the variable is defined. +2. **Redeploy after changes**: Any change to environment variables requires a redeploy of your function to take effect. +3. **Access variables correctly**: In your code, use `process.env.MY_VARIABLE` (for Node.js compatibility) or the platform-specific API if using another runtime. + +If you’re using a framework like Next.js, ensure your build process does not overwrite or ignore these variables. For more, see [Azion’s guide to environment variables](/en/documentation/products/edge-functions/environment-variables/). + +--- \ No newline at end of file diff --git a/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/nextjs/nextjs.mdx b/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/nextjs/nextjs.mdx index 86d3b3e79b..d589af823d 100644 --- a/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/nextjs/nextjs.mdx +++ b/src/content/docs/pt-br/pages/devtools/azion-edge-runtime/nextjs/nextjs.mdx @@ -20,9 +20,96 @@ Compatibilidade entre diferentes versões do Next.js e a Azion Web Platform. --- +## OpenNext + +O adaptador [`@aziontech/opennextjs-azion`](https://www.npmjs.com/package/@aziontech/opennextjs-azion) permite que você implemente aplicativos Next.js para [Functions da Azion](https://www.azion.com/pt-br/produtos/edge-functions/) usando o [runtime "de Node.js" do Next.js](https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes). + +### Introdução + +#### Novos aplicativos + +Para criar um novo aplicativo Next.js, pré-configurado para executar na Azion usando `@aziontech/opennextjs-azion`, execute: + +```shell +npx create-next-app@14.2.4 my-next-app --use-npm && cd my-next-app && npm install @aziontech/opennextjs-azion@latest +``` + +#### Aplicativos Next.js existentes + +[Siga o guia aqui](/azion/get-started) para usar [@aziontech/opennextjs-azion](https://www.npmjs.com/package/@aziontech/opennextjs-azion) com um aplicativo Next.js existente. + +### Versões do Next.js suportadas + +Todos os patch e versões menores do Next.js 15 e o menor patch do Next.js 14 são suportados. + +Para ajudar a melhorar a compatibilidade, incentivamos você a [relatar bugs](https://github.com/aziontech/opennextjs-azion/issues) e contribuir com código! + +### Recursos do Next.js suportados + +| Recurso | Suporte | Comentários | +|---|---|---| +| [App Router](https://nextjs.org/docs/app) | 🟢 | | +| [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) | 🟢 | | +| [Rotas dinâmicas](https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes) | 🟢 | | +| [Geração de site estático (SSG)](https://nextjs.org/docs/app/building-your-application/rendering/server-components#static-rendering-default) | 🟢 | | +| [Renderização no lado do servidor (SSR)](https://nextjs.org/docs/app/building-your-application/rendering/server-components) | 🟢 | | +| [Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware) | 🟢 | | +| [Node Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware#runtime) | 🟡 | Foi introduzido no 15.2, mas ainda não é suportado | +| [Otimização de imagem](https://nextjs.org/docs/app/building-your-application/optimizing/images) | 🔴 | | +| [Pré-renderização parcial (PPR)](https://nextjs.org/docs/app/building-your-application/rendering/partial-prerendering) | 🟢 | | +| [Pages Router](https://nextjs.org/docs/pages) | 🟢 | | +| [Geração estática incremental (ISR)](https://nextjs.org/docs/app/building-your-application/data-fetching/incremental-static-regeneration) | 🟢 | | +| [Suporte para after](https://nextjs.org/blog/next-15-rc#executing-code-after-a-response-with-nextafter-experimental) | 🟢 | | +| [Cache componível](https://nextjs.org/blog/composable-caching) | 🔴 | ('use cache') | + +:::note +As Functions da Azion têm um limite máximo de tamanho de 50 MB por função. Após compilar seu projeto, preste atenção ao tamanho comprimido (gzipped) do seu pacote de implementação — apenas o tamanho comprimido conta para esse limite. +Para mais detalhes, consulte a [documentação sobre limites de tamanho para Functions](/pt-br/documentacao/produtos/build/edge-application/edge-functions/#limites). +::: + +### Exemplos + +Para criar um novo aplicativo Next.js na Azion, você pode usar os seguintes projetos iniciantes e templates: + +#### Projetos iniciantes básicos + +- [Template Next.js + TypeScript + Tailwind](https://github.com/aziontech/azion-samples/tree/dev/templates/opennextjs/nextal-next-typescript-tailwind) — um template pronto para uso para construir aplicativos Next.js modernos nas Functions da Azion. +- [Node Playground (Next.js 13)](https://github.com/aziontech/bundler-examples/tree/main/examples/nextjs/node-playground-13) — um exemplo mostrando como executar Next.js 13 em um ambiente Node.js na Azion. + +Você pode usar esses repositórios para entender como configurar seu aplicativo Next.js para rodar na Azion, ou como um ponto de partida para seus próprios projetos. + +### Problemas conhecidos + +#### Configuração TS +- Seu `tsconfig.json` deve incluir a seguinte configuração: + +```json +"moduleResolution": "bundler" +``` + + Se isso não estiver configurado, você poderá encontrar problemas durante o processo de build ou execução. + +- Existe um problema conhecido com ESM e o arquivo `open-next.config.ts`. Se você tem um projeto mais antigo ou que depende de uma versão específica do TypeScript ou de uma configuração customizada, pode ser necessário: + - Reconfigurar seu projeto (por exemplo, definindo `moduleResolution: bundler` como acima), **ou** + - Add the following to your `tsconfig.json`: + +```json +"exclude": ["node_modules", "open-next.config.ts"] +``` + +Se isso funcionará depende da configuração do seu projeto. Em alguns casos, excluir `open-next.config.ts` permite que o build prossiga, mas você ainda pode encontrar erros, especialmente se seu projeto usar funcionalidades como `_app.mdx` ou outras configurações avançadas. Isso é particularmente relevante para projetos que não foram testados com essas configurações, e problemas também podem ocorrer em outros ambientes (como o pacote Cloudflare). + +#### Desenvolvimento local + +- Algumas aplicações podem usar Node.js ou APIs padrão web que não são totalmente suportadas pelo ambiente de desenvolvimento local da Azion. Entretanto, esses recursos podem estar disponíveis no runtime real da Azion. + +:::tip +Se sua aplicação não funcionar como esperado durante o desenvolvimento local, tente implementá-la na Azion antes de continuar a solução de problemas, pois ela pode funcionar corretamente no ambiente implementado. +::: + ## Next.js 14.x.y -| Funcionalidade | Suporte | Comentários | +| Feature | Support | Comments | |---|---|---| | Static Pages | 🟢 | | | SSG | 🟢 | | @@ -115,7 +202,7 @@ Digamos que você crie `pages/azion.js` exportando um React component. ```js export default function Azion() { - return
The easiest way to build, deploy, observe and secure modern applications.
+ return
A maneira mais fácil de construir, implementar, observar e proteger aplicações modernas.
} ``` diff --git a/src/content/docs/pt-br/pages/guias/open-next/comece-usar-opennext.mdx b/src/content/docs/pt-br/pages/guias/open-next/comece-usar-opennext.mdx new file mode 100644 index 0000000000..fc236bae0c --- /dev/null +++ b/src/content/docs/pt-br/pages/guias/open-next/comece-usar-opennext.mdx @@ -0,0 +1,188 @@ +--- +title: Comece com o OpenNext +description: >- + Comece com o OpenNext na Azion: crie ou adapte um app Next.js, configure o cache e o armazenamento para ISR/SSG, desenvolva localmente com o Azion CLI e faça o deploy para produção. +permalink: /documentacao/produtos/guias/opennext/como-comecar/ +meta_tags: >- + Compatibilidade Next.js, Azion Web Platform, SSR, SSG, Funcionalidades de Middleware, + Geração Estática, Renderização Server-side, Roteamento Next.js, Desempenho Next.js, Integrações Next.js +namespace: documentation_guides_opennext_get_started +--- + +O adaptador `@aziontech/opennextjs-azion` permite que você faça deploy de apps Next.js na Azion Web Platform. Este guia irá ajudá-lo a configurar um projeto Next.js novo ou existente para a Azion, configurar cache, desenvolver localmente e fazer o deploy para produção. + +--- + +### Pré-requisitos + +- [CLI Instalado](/pt-br/documentacao/produtos/azion-cli/visao-geral/#instalar-a-azion-cli). + +--- + +#### Criando um novo app Next.js + +Para criar um novo app Next.js pré-configurado para a Azion: + +```sh +npx create-next-app@14.2.4 my-next-app --use-npm +cd my-next-app +npm install @aziontech/opennextjs-azion@latest +``` + +Ou use um template inicial: + +- [Template Next.js + TypeScript + Tailwind](https://github.com/aziontech/azion-samples/tree/dev/templates/opennextjs/nextal-next-typescript-tailwind) +- [Node Playground (Next.js 13)](https://github.com/aziontech/bundler-examples/tree/main/examples/nextjs/node-playground-13) + +--- + +#### Apps Next.js existentes + +1. Instale o adaptador Azion: + +```sh +npm install @aziontech/opennextjs-azion@latest +``` + +2. Configure `open-next.config.ts`: + +Crie ou atualize `open-next.config.ts` no diretório raiz do seu projeto. Exemplo: + +```ts +import { defineAzionConfig } from "@aziontech/opennextjs-azion"; + +export default defineAzionConfig({ + // Veja /azion/caching para opções avançadas +}); +``` + +3. Atualize `tsconfig.json`: + +:::warning +Seu `tsconfig.json` deve incluir ```json "moduleResolution": "bundler" ```. Isto é necessário para o comportamento correto de build e runtime. +::: + +Se você encontrar problemas com ESM ou `open-next.config.ts`, pode ser necessário adicionar: + +```json +"exclude": ["node_modules", "open-next.config.ts"] +``` + +Veja [Problemas Conhecidos](/pt-br/documentacao/runtime-api/frameworks-suportados/nextjs/#problemas-conhecidos) para mais detalhes. + +1. Build e Deploy com Azion CLI: + +- `azion build`: Constrói seu app para a Azion. +- `azion preview`: Executa uma pré-visualização local usando o Azion CLI. +- `azion deploy`: Faz deploy na Azion Web Platform usando deploy remoto. + - ou `azion deploy --local` para fazer deploy na Azion Web Platform usando Deploy Local. + +5. Configure cache e armazenamento: + +Veja o [Guia de Cache](/azion/caching) para saber como configurar o Azion Object Storage e Cache para ISR/SSG. Exemplo de configuração Azion: + +```ts +AzionCache +Definição de tipo para a configuração de cache. +``` + +Propriedades: + +| Propriedade | Tipo | Descrição | +| --- | --- | --- | +| nome | string | Nome da configuração de cache. | +| staleness? | boolean | Se permite conteúdo obsoleto. | +| queryStringSort? | boolean | Se organiza parâmetros de string de consulta. | +| métodos? | CacheMethods | Métodos HTTP para cache. | +| post? | boolean | Se faz cache de requisições POST. | +| opções? | boolean | Se faz cache de requisições OPTIONS. | +| navegador? | BrowserCacheConfig | Configurações de cache para navegador. | +| navegador.maxAgeSeconds | number \| string | Idade máxima para cache do navegador em segundos. | +| edge? | EdgeCacheConfig | Configurações de cache. | +| edge.maxAgeSeconds | number \| string | Idade máxima para cache em segundos. | +| cacheByCookie? | CacheByCookieConfig | Cache por configurações de cookie. | +| cacheByCookie.option | 'ignore' \| 'varies' \| 'whitelist' \| 'blacklist' | Opção de cache por cookie. | +| cacheByCookie.list? | string[] | Lista de cookies para uso em cache. | +| cacheByQueryString? | CacheByQueryStringConfig | Cache por configurações de string de consulta. | +| cacheByQueryString.option | 'ignore' \| 'varies' \| 'whitelist' \| 'blacklist' | Opção de cache por string de consulta. | +| cacheByQueryString.list? | string[] | Lista de parâmetros de string de consulta para uso em cache. | + +```js +// azion.config.cjs +module.exports = { + build: { preset: "opennextjs", polyfills: true }, + origin: [{ name: "origin-storage-default", type: "object_storage" }], + functions: [{ name: "handler", path: ".edge/worker.js" }], + cache: [ + { + name: 'Default Cache', + browser: { maxAgeSeconds: 3600 }, + edge: { maxAgeSeconds: 7200 }, + }, + ], + rules: { + request: [ + { + name: "Set storage origin for _next/static", + match: "^/_next/static/", + behavior: { setOrigin: { name: "origin-storage-default", type: "object_storage" }, deliver: true }, + }, + { + name: "Deliver Static Assets", + match: ".(css|js|ttf|woff|woff2|pdf|svg|jpg|jpeg|gif|bmp|png|ico|mp4|json)$", + behavior: { setOrigin: { name: "origin-storage-default", type: "object_storage" }, deliver: true }, + }, + { + name: "Execute Function", + match: "^/", + behavior: { runFunction: "handler", forwardCookies: true }, + }, + ], + }, +}; +``` + +--- + +### Desenvolvimento Local + +Use o [Azion CLI](/pt-br/documentacao/produtos/cli/) para desenvolvimento local: + +```sh +azion dev +``` + +Isso executa sua aplicação localmente, simulando a plataforma Azion. Veja [Solução de Problemas](/pt-br/documentacao/produtos/guias/opennext/troubleshooting/) para dicas de depuração e monitoramento de logs. + +--- + +### Implementação + +Implemente seu app na Azion Web Platform: + +```sh +azion deploy +``` + +Ou use o Azion CLI para implementar na Azion Web Platform usando implementação local: + +```sh +azion deploy --local +``` + +--- + +### Melhores práticas e solução de problemas + +- Veja [Problemas Conhecidos](/pt-br/documentacao/runtime-api/frameworks-suportados/nextjs/#problemas-conhecidos) para acessar notas de configuração importantes. +- Veja [Solução de Problemas](/pt-br/documentacao/produtos/guias/opennext/troubleshooting/) para dicas de desenvolvimento local, logs e depuração. +- Explore [Exemplos](/pt-br/documentacao/runtime-api/frameworks-suportados/nextjs/#exemplos) para projetos iniciais e templates. +- Para cache avançado, [veja Cache](/azion/caching). + +:::tip +Algumas APIs do Node.js ou Web podem não ser totalmente suportadas no ambiente de desenvolvimento local da Azion, mas funcionarão em produção. Se você encontrar problemas localmente, tente fazer o deploy antes de tentar uma depuração profunda. +::: + +Agora você está pronto para construir, testar e implementar apps Next.js nas Functions Azion! + +--- \ No newline at end of file diff --git a/src/content/docs/pt-br/pages/guias/open-next/troubleshooting-opennext.mdx b/src/content/docs/pt-br/pages/guias/open-next/troubleshooting-opennext.mdx new file mode 100644 index 0000000000..b98598ccdd --- /dev/null +++ b/src/content/docs/pt-br/pages/guias/open-next/troubleshooting-opennext.mdx @@ -0,0 +1,161 @@ +--- +title: Solução de problemas de uma aplicação OpenNext +description: >- + Aprenda como solucionar problemas de apps OpenNext na Azion: execute localmente com o Azion CLI, monitore logs, use APIs de Eventos em Tempo Real, Metadados e GraphQL, corrija limites de tamanho e variáveis de ambiente. +permalink: /documentacao/produtos/guias/opennext/troubleshooting/ +meta_tags: >- + Compatibilidade Next.js, Azion Web Platform, SSR, SSG, Funcionalidades de Middleware, + Geração Estática, Renderização Server-side, Roteamento Next.js, Desempenho Next.js, Integrações Next.js +namespace: documentation_guides_opennext_troubleshooting +--- + +## 1. Desenvolvimento local e depuração com o Azion CLI + +O primeiro e mais crucial passo de solução de problemas é realizado antes mesmo do deployment. O Azion CLI permite que você execute sua função em um ambiente local que simula a plataforma Azion. + +**Comando Chave**: +```bash +azion dev +``` +Quando você executa esse comando na raiz do seu projeto, o CLI inicia um servidor local. Qualquer solicitação feita a esse servidor executará sua função, e saídas de `console.log`, bem como quaisquer erros, serão exibidas diretamente em seu terminal. + +**Benefícios**: +* **Feedback imediato**: Veja os resultados das suas alterações de código instantaneamente. +* **Economia de tempo**: Evita a necessidade de deployment para cada pequena alteração. +* **Ambiente controlado**: Depure a lógica da sua aplicação sem afetar o ambiente de produção. + +**Exemplo**: + +```javascript +// main.js +export default function myWorker(event) { + console.log("Função executada com sucesso!"); + return new Response('Olá Mundo'); +} +``` + +Depois de executar `azion dev` e acessar o servidor local, seu terminal exibirá: + +``` +Função executada com sucesso! +``` + +## 2. Monitoramento de logs em produção + +Quando sua aplicação estiver em produção, você precisará de ferramentas para observar seu comportamento em tempo real e analisar eventos passados. + +### Acesso em tempo real (Tailing) + +Para monitorar logs à medida que acontecem, use o argumento `--tail` com o Azion CLI. Isso cria uma sessão contínua que exibe novos logs à medida que são gerados. + +**Comando chave**: + +```bash +azion logs cells --tail +``` + +Este comando é ideal para depurar problemas que estão acontecendo atualmente ou para monitorar o comportamento da aplicação durante um novo deployment. + +### Visualização via Console da Azion (Eventos em Tempo Real) + +Para uma análise mais visual com mais opções de filtro, o Console da Azion é a ferramenta ideal. + +1. Acesse o **Gerenciador em Tempo Real**. +2. No menu, vá para **Observar > Eventos em Tempo Real**. +3. Selecione a guia do Console **Functions**. + +Nessa tela, você pode: + +* Visualizar todos os logs gerados por `console.log` em suas funções. +* Filtrar eventos por períodos de tempo (últimos 15 minutos, última hora, intervalo personalizado). +* Pesquisar mensagens de log específicas. +* Analisar informações detalhadas para cada evento, como `ID da Função` e `Timestamp`. + +## 3. Análise avançada com a API de metadados + +Frequentemente, o problema não está apenas no código, mas no contexto da solicitação (origem, cabeçalhos, etc.). A **API de Metadados** da Azion permite que suas funções acessem esses dados. Você pode registrar esses metadados para entender melhor o comportamento da sua aplicação. + +**Exemplo prático**: + +Imagine que você queira verificar de qual continente uma solicitação está vindo. + +```javascript +// main.js +export default function myWorker(event) { + const request = event.request; + const continentCode = request.metadata['geoip_continent_code']; + + console.log(`Solicitação recebida do continente: ${continentCode}`); + + // Lógica adicional baseada no continente... + + return new Response(`Olá, ${continentCode}!`); +} +``` + +Ao implementar este código e monitorar os logs com `azion logs cells --tail`, você verá mensagens como: + +``` +Solicitação recebida do continente: SA + +``` + +Isso permite que você depure lógica de roteamento, segurança (e.g., bloqueio por região) e personalização de conteúdo. + +## 4. Coleta estruturada de logs com a API GraphQL + +Para automação, integração com sistemas de monitoramento externos (como Datadog ou New Relic), ou para realizar análises complexas, a Azion fornece uma **API GraphQL**. + +Com ela, você pode executar consultas para buscar logs em um formato estruturado. + +**Ferramenta Chave**: O **GraphQL Playground**, disponível no Console da Azion, permite que você construa e teste suas consultas antes de integrá-las aos seus sistemas. + +**Exemplo de Consulta**: +Esta consulta obtém os 10 eventos de console mais recentes contendo uma linha de log específica. + +```graphql +query getConsoleEvents { + cellsConsoleEvents( + limit: 10, + filter: { + tsRange: {begin: "2024-09-28T12:00:00", end: "2024-09-28T13:00:00"}, + line: {contains: "Function failed"} + }, + orderBy: [ts_ASC] + ) { + ts + configurationId + functionId + line + } +} +``` + +## 5. O tamanho da função excede o limite + +A Azion impõe limites no tamanho das funções, o limite padrão é de 20MB. Se seu deployment falhar com um erro sobre o tamanho da função, normalmente significa que seu código empacotado é muito grande para a plataforma. + +Para resolver isso: + +1. **Analise seu pacote**: Use ferramentas como [Webpack Bundle Analyzer](https://www.npmjs.com/package/webpack-bundle-analyzer) ou [ESBuild Analyzer](https://esbuild.github.io/analyze/) para identificar dependências grandes. +2. **Remova dependências não usadas**: Audite seu `package.json` e código para pacotes desnecessários. +3. **Otimize importações**: Prefira importar funções específicas em vez de bibliotecas inteiras (por exemplo, `import { parse } from "date-fns"` em vez de `import * as dateFns from "date-fns"`). +4. **Aproveite o cache da Azion**: Mova ativos estáticos e arquivos grandes para o Armazenamento de Objetos ou CDN da Azion e faça referência a eles via URLs em vez de empacotá-los. + +Consulte [a documentação da Azion sobre limites de função](/pt-br/documentacao/produtos/build/edge-application/edge-functions/#limites) para restrições de tamanho atualizadas. + +--- + +## 6. Minhas variáveis de ambiente não estão disponíveis na Função + +A Azion permite que você defina variáveis de ambiente para suas funções, mas elas devem ser configuradas explicitamente no console da Azion ou via API. + +Se seu código não consegue acessar uma variável de ambiente esperada: + +1. **Verifique o console da Azion**: Vá para sua Aplicação > Funções > Variáveis de Ambiente e assegure-se de que a variável esteja definida. +2. **Refaça o deployment após alterações**: Qualquer alteração nas variáveis de ambiente requer um novo deployment da sua função para entrar em vigor. +3. **Acesse as variáveis corretamente**: No seu código, use `process.env.MY_VARIABLE` (para compatibilidade com Node.js) ou a API específica da plataforma se estiver usando outro runtime. + +Se você estiver usando um framework como o Next.js, assegure-se de que seu processo de build não sobrescreva ou ignore essas variáveis. Para mais informações, veja [o guia da Azion sobre variáveis de ambiente](/pt-br/documentacao/produtos/edge-functions/environment-variables/). + +--- \ No newline at end of file