` en las tablas para evitar errores de hidratación.
-### Preserve Whitespaces Configuration
+### Configuración de Preservación de Espacios en Blanco
-When using the hydration feature, we recommend using the default setting of `false` for `preserveWhitespaces`. If this setting is not in your tsconfig, the value will be `false` and no changes are required. If you choose to enable preserving whitespaces by adding `preserveWhitespaces: true` to your tsconfig, it is possible you may encounter issues with hydration. This is not yet a fully supported configuration.
+Cuando se usa la característica de hidratación, recomendamos usar la configuración predeterminada de `false` para `preserveWhitespaces`. Si esta configuración no está en tu tsconfig, el valor será `false` y no se requieren cambios. Si eliges habilitar la preservación de espacios en blanco agregando `preserveWhitespaces: true` a tu tsconfig, es posible que encuentres problemas con la hidratación. Esta no es todavía una configuración completamente soportada.
-HELPFUL: Make sure that this setting is set **consistently** in `tsconfig.server.json` for your server and `tsconfig.app.json` for your browser builds. A mismatched value will cause hydration to break.
+ÚTIL: Asegúrate de que esta configuración esté establecida **de forma consistente** en `tsconfig.server.json` para tu servidor y en `tsconfig.app.json` para tus compilaciones del navegador. Un valor inconsistente causará que la hidratación falle.
-If you choose to set this setting in your tsconfig, we recommend to set it only in `tsconfig.app.json` which by default the `tsconfig.server.json` will inherit it from.
+Si eliges establecer esta configuración en tu tsconfig, recomendamos establecerla solo en `tsconfig.app.json`, de la cual `tsconfig.server.json` la heredará de forma predeterminada.
-### Custom or Noop Zone.js are not yet supported
+### Zone.js personalizado o Noop aún no son compatibles
-Hydration relies on a signal from Zone.js when it becomes stable inside an application, so that Angular can start the serialization process on the server or post-hydration cleanup on the client to remove DOM nodes that remained unclaimed.
+La hidratación depende de una señal de Zone.js cuando se vuelve estable dentro de una aplicación, para que Angular pueda iniciar el proceso de serialización en el servidor o la limpieza post-hidratación en el cliente para eliminar los nodos del DOM que permanecieron sin reclamar.
-Providing a custom or a "noop" Zone.js implementation may lead to a different timing of the "stable" event, thus triggering the serialization or the cleanup too early or too late. This is not yet a fully supported configuration and you may need to adjust the timing of the `onStable` event in the custom Zone.js implementation.
+Proporcionar una implementación personalizada o "noop" de Zone.js puede llevar a un tiempo diferente para el evento "stable", activando así la serialización o la limpieza demasiado pronto o demasiado tarde. Esta no es todavía una configuración completamente soportada y puede que necesites ajustar el tiempo del evento `onStable` en la implementación personalizada de Zone.js.
-## Errors
+## Errores
-There are several hydration related errors you may encounter ranging from node mismatches to cases when the `ngSkipHydration` was used on an invalid host node. The most common error case that may occur is due to direct DOM manipulation using native APIs that results in hydration being unable to find or match the expected DOM tree structure on the client that was rendered by the server. The other case you may encounter this type of error was mentioned in the [Valid HTML structure](#valid-html-structure) section earlier. So, make sure the HTML in your templates are using valid structure, and you'll avoid that error case.
+Hay varios errores relacionados con la hidratación que puedes encontrar, desde discrepancias de nodos hasta casos donde `ngSkipHydration` fue usado en un nodo host inválido. El caso de error más común que puede ocurrir se debe a la manipulación directa del DOM usando APIs nativas, lo que resulta en que la hidratación no puede encontrar o hacer coincidir la estructura del árbol del DOM esperada en el cliente que fue renderizada por el servidor. El otro caso donde puedes encontrar este tipo de error fue mencionado en la sección [Estructura HTML válida](#estructura-html-válida) anterior. Por lo tanto, asegúrate de que el HTML en tus plantillas use estructura válida y evitarás ese caso de error.
-For a full reference on hydration related errors, visit the [Errors Reference Guide](/errors).
+Para una referencia completa de los errores relacionados con la hidratación, visita la [Guía de Referencia de Errores](/errors).
-## How to skip hydration for particular components
+## Cómo omitir la hidratación para componentes específicos
-Some components may not work properly with hydration enabled due to some of the aforementioned issues, like [Direct DOM Manipulation](#direct-dom-manipulation). As a workaround, you can add the `ngSkipHydration` attribute to a component's tag in order to skip hydrating the entire component.
+Algunos componentes pueden no funcionar correctamente con la hidratación habilitada debido a algunos de los problemas mencionados anteriormente, como la [Manipulación Directa del DOM](#manipulación-directa-del-dom). Como solución alternativa, puedes agregar el atributo `ngSkipHydration` a la etiqueta de un componente para omitir la hidratación del componente completo.
```angular-html
```
-Alternatively you can set `ngSkipHydration` as a host binding.
+Alternativamente, puedes establecer `ngSkipHydration` como un host binding.
```typescript
@Component({
@@ -164,23 +164,23 @@ Alternatively you can set `ngSkipHydration` as a host binding.
class ExampleComponent {}
```
-The `ngSkipHydration` attribute will force Angular to skip hydrating the entire component and its children. Using this attribute means that the component will behave as if hydration is not enabled, meaning it will destroy and re-render itself.
+El atributo `ngSkipHydration` forzará a Angular a omitir la hidratación del componente completo y sus hijos. Usar este atributo significa que el componente se comportará como si la hidratación no estuviera habilitada, lo que significa que se destruirá y volverá a renderizarse.
-HELPFUL: This will fix rendering issues, but it means that for this component (and its children), you don't get the benefits of hydration. You will need to adjust your component's implementation to avoid hydration-breaking patterns (i.e. Direct DOM Manipulation) to be able to remove the skip hydration annotation.
+ÚTIL: Esto solucionará los problemas de renderización, pero significa que para este componente (y sus hijos), no obtienes los beneficios de la hidratación. Necesitarás ajustar la implementación de tu componente para evitar patrones que rompan la hidratación (es decir, la Manipulación Directa del DOM) para poder eliminar la anotación de omisión de hidratación.
-The `ngSkipHydration` attribute can only be used on component host nodes. Angular throws an error if this attribute is added to other nodes.
+El atributo `ngSkipHydration` solo puede usarse en nodos host de componentes. Angular lanza un error si este atributo se agrega a otros nodos.
-Keep in mind that adding the `ngSkipHydration` attribute to your root application component would effectively disable hydration for your entire application. Be careful and thoughtful about using this attribute. It is intended as a last resort workaround. Components that break hydration should be considered bugs that need to be fixed.
+Ten en cuenta que agregar el atributo `ngSkipHydration` a tu componente raíz de la aplicación deshabilitaría efectivamente la hidratación para toda tu aplicación. Sé cuidadoso y reflexivo al usar este atributo. Está pensado como una solución alternativa de último recurso. Los componentes que rompen la hidratación deben considerarse errores que necesitan ser corregidos.
-## Hydration Timing and Application Stability
+## Tiempo de Hidratación y Estabilidad de la Aplicación
-Application stability is an important part of the hydration process. Hydration and any post-hydration processes only occur once the application has reported stability. There are a number of ways that stability can be delayed. Examples include setting timeouts and intervals, unresolved promises, and pending microtasks. In those cases, you may encounter the [Application remains unstable](errors/NG0506) error, which indicates that your app has not yet reached the stable state after 10 seconds. If you're finding that your application is not hydrating right away, take a look at what is impacting application stability and refactor to avoid causing these delays.
+La estabilidad de la aplicación es una parte importante del proceso de hidratación. La hidratación y cualquier proceso post-hidratación solo ocurren una vez que la aplicación ha reportado estabilidad. Hay varias formas en que la estabilidad puede retrasarse. Los ejemplos incluyen la configuración de timeouts e intervalos, promesas sin resolver y microtareas pendientes. En esos casos, puedes encontrar el error [La aplicación permanece inestable](errors/NG0506), que indica que tu aplicación no ha alcanzado el estado estable después de 10 segundos. Si descubres que tu aplicación no se está hidratando de inmediato, examina qué está afectando la estabilidad de la aplicación y refactoriza para evitar causar estos retrasos.
## I18N
-HELPFUL: By default, Angular will skip hydration for components that use i18n blocks, effectively re-rendering those components from scratch.
+ÚTIL: De forma predeterminada, Angular omitirá la hidratación para los componentes que usan bloques i18n, efectivamente re-renderizando esos componentes desde cero.
-To enable hydration for i18n blocks, you can add [`withI18nSupport`](/api/platform-browser/withI18nSupport) to your `provideClientHydration` call.
+Para habilitar la hidratación para bloques i18n, puedes agregar [`withI18nSupport`](/api/platform-browser/withI18nSupport) a tu llamada a `provideClientHydration`.
```typescript
import {
@@ -195,18 +195,18 @@ bootstrapApplication(AppComponent, {
});
```
-## Consistent rendering across server-side and client-side
+## Renderización consistente entre el servidor y el cliente
-Avoid introducing `@if` blocks and other conditionals that display different content when server-side rendering than client-side rendering, such as using an `@if` block with Angular's `isPlatformBrowser` function. These rendering differences cause layout shifts, negatively impacting end-user experience and core web vitals.
+Evita introducir bloques `@if` y otros condicionales que muestren contenido diferente al renderizar en el servidor en comparación con el cliente, como usar un bloque `@if` con la función `isPlatformBrowser` de Angular. Estas diferencias de renderización causan desplazamientos del diseño, afectando negativamente la experiencia del usuario final y los core web vitals.
-## Third Party Libraries with DOM Manipulation
+## Bibliotecas de Terceros con Manipulación del DOM
-There are a number of third party libraries that depend on DOM manipulation to be able to render. D3 charts is a prime example. These libraries worked without hydration, but they may cause DOM mismatch errors when hydration is enabled. For now, if you encounter DOM mismatch errors using one of these libraries, you can add the `ngSkipHydration` attribute to the component that renders using that library.
+Hay varias bibliotecas de terceros que dependen de la manipulación del DOM para poder renderizar. Los gráficos D3 son un ejemplo claro. Estas bibliotecas funcionaban sin hidratación, pero pueden causar errores de discrepancia del DOM cuando la hidratación está habilitada. Por ahora, si encuentras errores de discrepancia del DOM usando una de estas bibliotecas, puedes agregar el atributo `ngSkipHydration` al componente que renderiza usando esa biblioteca.
-## Third Party Scripts with DOM Manipulation
+## Scripts de Terceros con Manipulación del DOM
-Many third party scripts, such as ad trackers and analytics, modify the DOM before hydration can occur. These scripts may cause hydration errors because the page no longer matches the structure expected by Angular. Prefer deferring this type of script until after hydration whenever possible. Consider using [`AfterNextRender`](api/core/afterNextRender) to delay the script until post-hydration processes have occurred.
+Muchos scripts de terceros, como rastreadores de anuncios y análisis, modifican el DOM antes de que la hidratación pueda ocurrir. Estos scripts pueden causar errores de hidratación porque la página ya no coincide con la estructura esperada por Angular. Prefiere diferir este tipo de script hasta después de la hidratación siempre que sea posible. Considera usar [`AfterNextRender`](api/core/afterNextRender) para retrasar el script hasta que los procesos post-hidratación hayan ocurrido.
-## Incremental Hydration
+## Hidratación Incremental
-Incremental hydration is an advanced form of hydration that allows for more granular control over when hydration happens. See the [incremental hydration guide](guide/incremental-hydration) for more information.
+La hidratación incremental es una forma avanzada de hidratación que permite un control más granular sobre cuándo ocurre la hidratación. Consulta la [guía de hidratación incremental](guide/incremental-hydration) para más información.
diff --git a/adev-es/src/content/guide/incremental-hydration.en.md b/adev-es/src/content/guide/incremental-hydration.en.md
new file mode 100644
index 0000000..dab1cb4
--- /dev/null
+++ b/adev-es/src/content/guide/incremental-hydration.en.md
@@ -0,0 +1,210 @@
+# Incremental Hydration
+
+**Incremental hydration** is an advanced type of [hydration](guide/hydration) that can leave sections of your application dehydrated and _incrementally_ trigger hydration of those sections as they are needed.
+
+## Why use incremental hydration?
+
+Incremental hydration is a performance improvement that builds on top of full application hydration. It can produce smaller initial bundles while still providing an end-user experience that is comparable to a full application hydration experience. Smaller bundles improve initial load times, reducing [First Input Delay (FID)](https://web.dev/fid) and [Cumulative Layout Shift (CLS)](https://web.dev/cls).
+
+Incremental hydration also lets you use deferrable views (`@defer`) for content that may not have been deferrable before. Specifically, you can now use deferrable views for content that is above the fold. Prior to incremental hydration, putting a `@defer` block above the fold would result in placeholder content rendering and then being replaced by the `@defer` block's main template content. This would result in a layout shift. Incremental hydration means the main template of the `@defer` block will render with no layout shift on hydration.
+
+## How do you enable incremental hydration in Angular?
+
+You can enable incremental hydration for applications that already use server-side rendering (SSR) with hydration. Follow the [Angular SSR Guide](guide/ssr) to enable server-side rendering and the [Angular Hydration Guide](guide/hydration) to enable hydration first.
+
+Enable incremental hydration by adding the `withIncrementalHydration()` function to the `provideClientHydration` provider.
+
+```typescript
+import {
+ bootstrapApplication,
+ provideClientHydration,
+ withIncrementalHydration,
+} from '@angular/platform-browser';
+...
+
+bootstrapApplication(AppComponent, {
+ providers: [provideClientHydration(withIncrementalHydration())]
+});
+```
+
+Incremental Hydration depends on and enables [event replay](guide/hydration#capturing-and-replaying-events) automatically. If you already have `withEventReplay()` in your list, you can safely remove it after enabling incremental hydration.
+
+## How does incremental hydration work?
+
+Incremental hydration builds on top of full-application [hydration](guide/hydration), [deferrable views](guide/defer), and [event replay](guide/hydration#capturing-and-replaying-events). With incremental hydration, you can add additional triggers to `@defer` blocks that define incremental hydration boundaries. Adding a `hydrate` trigger to a defer block tells Angular that it should load that defer block's dependencies during server-side rendering and render the main template rather than the `@placeholder`. When client-side rendering, the dependencies are still deferred, and the defer block content stays dehydrated until its `hydrate` trigger fires. That trigger tells the defer block to fetch its dependencies and hydrate the content. Any browser events, specifically those that match listeners registered in your component, that are triggered by the user prior to hydration are queued up and replayed once the hydration process is complete.
+
+## Controlling hydration of content with triggers
+
+You can specify **hydrate triggers** that control when Angular loads and hydrates deferred content. These are additional triggers that can be used alongside regular `@defer` triggers.
+
+Each `@defer` block may have multiple hydrate event triggers, separated with a semicolon (`;`). Angular triggers hydration when _any_ of the triggers fire.
+
+There are three types of hydrate triggers: `hydrate on`, `hydrate when`, and `hydrate never`.
+
+### `hydrate on`
+
+`hydrate on` specifies a condition for when hydration is triggered for the `@defer` block.
+
+The available triggers are as follows:
+
+| Trigger | Description |
+| --------------------------------------------------- | ---------------------------------------------------------------------- |
+| [`hydrate on idle`](#hydrate-on-idle) | Triggers when the browser is idle. |
+| [`hydrate on viewport`](#hydrate-on-viewport) | Triggers when specified content enters the viewport |
+| [`hydrate on interaction`](#hydrate-on-interaction) | Triggers when the user interacts with specified element |
+| [`hydrate on hover`](#hydrate-on-hover) | Triggers when the mouse hovers over specified area |
+| [`hydrate on immediate`](#hydrate-on-immediate) | Triggers immediately after non-deferred content has finished rendering |
+| [`hydrate on timer`](#hydrate-on-timer) | Triggers after a specific duration |
+
+#### `hydrate on idle`
+
+The `hydrate on idle` trigger loads the deferrable view's dependencies and hydrates the content once the browser has reached an idle state, based on `requestIdleCallback`.
+
+```angular-html
+@defer (hydrate on idle) {
+
+} @placeholder {
+ Large component placeholder
+}
+```
+
+#### `hydrate on viewport`
+
+The `hydrate on viewport` trigger loads the deferrable view's dependencies and hydrates the corresponding page of the app when the specified content enters the viewport using the
+[Intersection Observer API](https://developer.mozilla.org/docs/Web/API/Intersection_Observer_API).
+
+```angular-html
+@defer (hydrate on viewport) {
+
+} @placeholder {
+ Large component placeholder
+}
+```
+
+#### `hydrate on interaction`
+
+The `hydrate on interaction` trigger loads the deferrable view's dependencies and hydrates the content when the user interacts with the specified element through
+`click` or `keydown` events.
+
+```angular-html
+@defer (hydrate on interaction) {
+
+} @placeholder {
+ Large component placeholder
+}
+```
+
+#### `hydrate on hover`
+
+The `hydrate on hover` trigger loads the deferrable view's dependencies and hydrates the content when the mouse has hovered over the triggered area through the
+`mouseover` and `focusin` events.
+
+```angular-html
+@defer (hydrate on hover) {
+
+} @placeholder {
+ Large component placeholder
+}
+```
+
+#### `hydrate on immediate`
+
+The `hydrate on immediate` trigger loads the deferrable view's dependencies and hydrates the content immediately. This means that the deferred block loads as soon
+as all other non-deferred content has finished rendering.
+
+```angular-html
+@defer (hydrate on immediate) {
+
+} @placeholder {
+ Large component placeholder
+}
+```
+
+#### `hydrate on timer`
+
+The `hydrate on timer` trigger loads the deferrable view's dependencies and hydrates the content after a specified duration.
+
+```angular-html
+@defer (hydrate on timer(500ms)) {
+
+} @placeholder {
+ Large component placeholder
+}
+```
+
+The duration parameter must be specified in milliseconds (`ms`) or seconds (`s`).
+
+### `hydrate when`
+
+The `hydrate when` trigger accepts a custom conditional expression and loads the deferrable view's dependencies and hydrates the content when the
+condition becomes truthy.
+
+```angular-html
+@defer (hydrate when condition) {
+
+} @placeholder {
+ Large component placeholder
+}
+```
+
+NOTE: `hydrate when` conditions only trigger when they are the top-most dehydrated `@defer` block. The condition provided for the trigger is
+specified in the parent component, which needs to exist before it can be triggered. If the parent block is dehydrated, that expression will not yet
+be resolvable by Angular.
+
+### `hydrate never`
+
+The `hydrate never` allows users to specify that the content in the defer block should remain dehydrated indefinitely, effectively becoming static
+content. Note that this applies to the initial render only. During a subsequent client-side render, a `@defer` block with `hydrate never` would
+still fetch dependencies, as hydration only applies to initial load of server-side rendered content. In the example below, subsequent client-side
+renders would load the `@defer` block dependencies on viewport.
+
+```angular-html
+@defer (on viewport; hydrate never) {
+
+} @placeholder {
+ Large component placeholder
+}
+```
+
+NOTE: Using `hydrate never` prevents hydration of the entire nested subtree of a given `@defer` block. No other `hydrate` triggers fire for content nested underneath that block.
+
+## Hydrate triggers alongside regular triggers
+
+Hydrate triggers are additional triggers that are used alongside regular triggers on a `@defer` block. Hydration is an initial load optimization, and that means hydrate triggers only apply to that initial load. Any subsequent client side render will still use the regular trigger.
+
+```angular-html
+@defer (on idle; hydrate on interaction) {
+
+} @placeholder{
+ Example Placeholder
+}
+```
+
+In this example, on the initial load, the `hydrate on interaction` applies. Hydration will be triggered on interaction with the ` ` component. On any subsequent page load that is client-side rendered, for example when a user clicks a routerLink that loads a page with this component, the `on idle` will apply.
+
+## How does incremental hydration work with nested `@defer` blocks?
+
+Angular's component and dependency system is hierarchical, which means hydrating any component requires all of its parents also be hydrated. So if hydration is triggered for a child `@defer` block of a nested set of dehydrated `@defer` blocks, hydration is triggered from the top-most dehydrated `@defer` block down to the triggered child and fire in that order.
+
+```angular-html
+@defer (hydrate on interaction) {
+
+ @defer (hydrate on hover) {
+
+ } @placeholder {
+ Child placeholder
+ }
+} @placeholder{
+ Parent Placeholder
+}
+```
+
+In the above example, hovering over the nested `@defer` block triggers hydration. The parent `@defer` block with the ` ` hydrates first, then the child `@defer` block with ` ` hydrates after.
+
+## Constraints
+
+Incremental hydration has the same constraints as full-application hydration, including limits on direct DOM manipulation and requiring valid HTML structure. Visit the [Hydration guide constraints](guide/hydration#constraints) section for more details.
+
+## Do I still need to specify `@placeholder` blocks?
+
+Yes. `@placeholder` block content is not used for incremental hydration, but a `@placeholder` is still necessary for subsequent client-side rendering cases. If your content was not on the route that was part of the initial load, then any navigation to the route that has your `@defer` block content renders like a regular `@defer` block. So the `@placeholder` is rendered in those client-side rendering cases.
diff --git a/adev-es/src/content/guide/incremental-hydration.md b/adev-es/src/content/guide/incremental-hydration.md
index dab1cb4..0931190 100644
--- a/adev-es/src/content/guide/incremental-hydration.md
+++ b/adev-es/src/content/guide/incremental-hydration.md
@@ -1,18 +1,18 @@
-# Incremental Hydration
+# Hidratación Incremental
-**Incremental hydration** is an advanced type of [hydration](guide/hydration) that can leave sections of your application dehydrated and _incrementally_ trigger hydration of those sections as they are needed.
+La **hidratación incremental** es un tipo avanzado de [hidratación](guide/hydration) que puede dejar secciones de tu aplicación deshidratadas y activar _incrementalmente_ la hidratación de esas secciones a medida que se necesitan.
-## Why use incremental hydration?
+## ¿Por qué usar la hidratación incremental?
-Incremental hydration is a performance improvement that builds on top of full application hydration. It can produce smaller initial bundles while still providing an end-user experience that is comparable to a full application hydration experience. Smaller bundles improve initial load times, reducing [First Input Delay (FID)](https://web.dev/fid) and [Cumulative Layout Shift (CLS)](https://web.dev/cls).
+La hidratación incremental es una mejora de rendimiento que se construye sobre la hidratación completa de la aplicación. Puede producir bundles iniciales más pequeños y al mismo tiempo proporcionar una experiencia de usuario final comparable a la de una hidratación completa de la aplicación. Los bundles más pequeños mejoran los tiempos de carga inicial, reduciendo el [First Input Delay (FID)](https://web.dev/fid) y el [Cumulative Layout Shift (CLS)](https://web.dev/cls).
-Incremental hydration also lets you use deferrable views (`@defer`) for content that may not have been deferrable before. Specifically, you can now use deferrable views for content that is above the fold. Prior to incremental hydration, putting a `@defer` block above the fold would result in placeholder content rendering and then being replaced by the `@defer` block's main template content. This would result in a layout shift. Incremental hydration means the main template of the `@defer` block will render with no layout shift on hydration.
+La hidratación incremental también te permite usar vistas diferibles (`@defer`) para contenido que quizás no podía diferirse antes. Específicamente, ahora puedes usar vistas diferibles para contenido que está sobre el pliegue. Antes de la hidratación incremental, colocar un bloque `@defer` sobre el pliegue resultaba en que el contenido del placeholder se renderizaba y luego era reemplazado por el contenido de la plantilla principal del bloque `@defer`. Esto provocaba un desplazamiento del diseño. La hidratación incremental significa que la plantilla principal del bloque `@defer` se renderizará sin desplazamiento del diseño en la hidratación.
-## How do you enable incremental hydration in Angular?
+## ¿Cómo se habilita la hidratación incremental en Angular?
-You can enable incremental hydration for applications that already use server-side rendering (SSR) with hydration. Follow the [Angular SSR Guide](guide/ssr) to enable server-side rendering and the [Angular Hydration Guide](guide/hydration) to enable hydration first.
+Puedes habilitar la hidratación incremental para aplicaciones que ya usan renderización del lado del servidor (SSR) con hidratación. Sigue la [Guía de SSR en Angular](guide/ssr) para habilitar la renderización del lado del servidor y la [Guía de Hidratación en Angular](guide/hydration) para habilitar la hidratación primero.
-Enable incremental hydration by adding the `withIncrementalHydration()` function to the `provideClientHydration` provider.
+Habilita la hidratación incremental añadiendo la función `withIncrementalHydration()` al proveedor `provideClientHydration`.
```typescript
import {
@@ -27,38 +27,38 @@ bootstrapApplication(AppComponent, {
});
```
-Incremental Hydration depends on and enables [event replay](guide/hydration#capturing-and-replaying-events) automatically. If you already have `withEventReplay()` in your list, you can safely remove it after enabling incremental hydration.
+La hidratación incremental depende del [event replay](guide/hydration#captura-y-reproducción-de-eventos) y lo habilita automáticamente. Si ya tienes `withEventReplay()` en tu lista, puedes eliminarlo de forma segura después de habilitar la hidratación incremental.
-## How does incremental hydration work?
+## ¿Cómo funciona la hidratación incremental?
-Incremental hydration builds on top of full-application [hydration](guide/hydration), [deferrable views](guide/defer), and [event replay](guide/hydration#capturing-and-replaying-events). With incremental hydration, you can add additional triggers to `@defer` blocks that define incremental hydration boundaries. Adding a `hydrate` trigger to a defer block tells Angular that it should load that defer block's dependencies during server-side rendering and render the main template rather than the `@placeholder`. When client-side rendering, the dependencies are still deferred, and the defer block content stays dehydrated until its `hydrate` trigger fires. That trigger tells the defer block to fetch its dependencies and hydrate the content. Any browser events, specifically those that match listeners registered in your component, that are triggered by the user prior to hydration are queued up and replayed once the hydration process is complete.
+La hidratación incremental se construye sobre la [hidratación](guide/hydration) completa de la aplicación, las [vistas diferibles](guide/defer) y el [event replay](guide/hydration#captura-y-reproducción-de-eventos). Con la hidratación incremental, puedes añadir disparadores adicionales a los bloques `@defer` que definen los límites de hidratación incremental. Añadir un disparador `hydrate` a un bloque defer le indica a Angular que debe cargar las dependencias de ese bloque defer durante la renderización del lado del servidor y renderizar la plantilla principal en lugar del `@placeholder`. Al renderizar del lado del cliente, las dependencias siguen siendo diferidas y el contenido del bloque defer permanece deshidratado hasta que su disparador `hydrate` se activa. Ese disparador le indica al bloque defer que obtenga sus dependencias e hidrate el contenido. Cualquier evento del navegador, específicamente aquellos que coinciden con los escuchadores registrados en tu componente, que sean activados por el usuario antes de la hidratación se ponen en cola y se reproducen una vez que el proceso de hidratación se completa.
-## Controlling hydration of content with triggers
+## Controlando la hidratación del contenido con disparadores
-You can specify **hydrate triggers** that control when Angular loads and hydrates deferred content. These are additional triggers that can be used alongside regular `@defer` triggers.
+Puedes especificar **disparadores de hidratación** que controlen cuándo Angular carga e hidrata el contenido diferido. Estos son disparadores adicionales que pueden usarse junto con los disparadores regulares de `@defer`.
-Each `@defer` block may have multiple hydrate event triggers, separated with a semicolon (`;`). Angular triggers hydration when _any_ of the triggers fire.
+Cada bloque `@defer` puede tener múltiples disparadores de evento de hidratación, separados por punto y coma (`;`). Angular activa la hidratación cuando _cualquiera_ de los disparadores se activa.
-There are three types of hydrate triggers: `hydrate on`, `hydrate when`, and `hydrate never`.
+Hay tres tipos de disparadores de hidratación: `hydrate on`, `hydrate when` y `hydrate never`.
### `hydrate on`
-`hydrate on` specifies a condition for when hydration is triggered for the `@defer` block.
+`hydrate on` especifica una condición para cuando se activa la hidratación del bloque `@defer`.
-The available triggers are as follows:
+Los disparadores disponibles son los siguientes:
-| Trigger | Description |
-| --------------------------------------------------- | ---------------------------------------------------------------------- |
-| [`hydrate on idle`](#hydrate-on-idle) | Triggers when the browser is idle. |
-| [`hydrate on viewport`](#hydrate-on-viewport) | Triggers when specified content enters the viewport |
-| [`hydrate on interaction`](#hydrate-on-interaction) | Triggers when the user interacts with specified element |
-| [`hydrate on hover`](#hydrate-on-hover) | Triggers when the mouse hovers over specified area |
-| [`hydrate on immediate`](#hydrate-on-immediate) | Triggers immediately after non-deferred content has finished rendering |
-| [`hydrate on timer`](#hydrate-on-timer) | Triggers after a specific duration |
+| Disparador | Descripción |
+| --------------------------------------------------- | ------------------------------------------------------------------------------- |
+| [`hydrate on idle`](#hydrate-on-idle) | Se activa cuando el navegador está inactivo. |
+| [`hydrate on viewport`](#hydrate-on-viewport) | Se activa cuando el contenido especificado entra en el viewport |
+| [`hydrate on interaction`](#hydrate-on-interaction) | Se activa cuando el usuario interactúa con el elemento especificado |
+| [`hydrate on hover`](#hydrate-on-hover) | Se activa cuando el mouse se desplaza sobre el área especificada |
+| [`hydrate on immediate`](#hydrate-on-immediate) | Se activa inmediatamente después de que el contenido no diferido termina de renderizarse |
+| [`hydrate on timer`](#hydrate-on-timer) | Se activa después de una duración específica |
#### `hydrate on idle`
-The `hydrate on idle` trigger loads the deferrable view's dependencies and hydrates the content once the browser has reached an idle state, based on `requestIdleCallback`.
+El disparador `hydrate on idle` carga las dependencias de la vista diferible e hidrata el contenido una vez que el navegador ha alcanzado un estado inactivo, basándose en `requestIdleCallback`.
```angular-html
@defer (hydrate on idle) {
@@ -70,8 +70,8 @@ The `hydrate on idle` trigger loads the deferrable view's dependencies and hydra
#### `hydrate on viewport`
-The `hydrate on viewport` trigger loads the deferrable view's dependencies and hydrates the corresponding page of the app when the specified content enters the viewport using the
-[Intersection Observer API](https://developer.mozilla.org/docs/Web/API/Intersection_Observer_API).
+El disparador `hydrate on viewport` carga las dependencias de la vista diferible e hidrata la página correspondiente de la aplicación cuando el contenido especificado entra en el viewport usando la
+[API Intersection Observer](https://developer.mozilla.org/docs/Web/API/Intersection_Observer_API).
```angular-html
@defer (hydrate on viewport) {
@@ -83,8 +83,8 @@ The `hydrate on viewport` trigger loads the deferrable view's dependencies and h
#### `hydrate on interaction`
-The `hydrate on interaction` trigger loads the deferrable view's dependencies and hydrates the content when the user interacts with the specified element through
-`click` or `keydown` events.
+El disparador `hydrate on interaction` carga las dependencias de la vista diferible e hidrata el contenido cuando el usuario interactúa con el elemento especificado a través de eventos
+`click` o `keydown`.
```angular-html
@defer (hydrate on interaction) {
@@ -96,8 +96,8 @@ The `hydrate on interaction` trigger loads the deferrable view's dependencies an
#### `hydrate on hover`
-The `hydrate on hover` trigger loads the deferrable view's dependencies and hydrates the content when the mouse has hovered over the triggered area through the
-`mouseover` and `focusin` events.
+El disparador `hydrate on hover` carga las dependencias de la vista diferible e hidrata el contenido cuando el mouse se ha desplazado sobre el área activada a través de los eventos
+`mouseover` y `focusin`.
```angular-html
@defer (hydrate on hover) {
@@ -109,8 +109,7 @@ The `hydrate on hover` trigger loads the deferrable view's dependencies and hydr
#### `hydrate on immediate`
-The `hydrate on immediate` trigger loads the deferrable view's dependencies and hydrates the content immediately. This means that the deferred block loads as soon
-as all other non-deferred content has finished rendering.
+El disparador `hydrate on immediate` carga las dependencias de la vista diferible e hidrata el contenido inmediatamente. Esto significa que el bloque diferido se carga tan pronto como todo el demás contenido no diferido termina de renderizarse.
```angular-html
@defer (hydrate on immediate) {
@@ -122,7 +121,7 @@ as all other non-deferred content has finished rendering.
#### `hydrate on timer`
-The `hydrate on timer` trigger loads the deferrable view's dependencies and hydrates the content after a specified duration.
+El disparador `hydrate on timer` carga las dependencias de la vista diferible e hidrata el contenido después de una duración especificada.
```angular-html
@defer (hydrate on timer(500ms)) {
@@ -132,12 +131,11 @@ The `hydrate on timer` trigger loads the deferrable view's dependencies and hydr
}
```
-The duration parameter must be specified in milliseconds (`ms`) or seconds (`s`).
+El parámetro de duración debe especificarse en milisegundos (`ms`) o segundos (`s`).
### `hydrate when`
-The `hydrate when` trigger accepts a custom conditional expression and loads the deferrable view's dependencies and hydrates the content when the
-condition becomes truthy.
+El disparador `hydrate when` acepta una expresión condicional personalizada y carga las dependencias de la vista diferible e hidrata el contenido cuando la condición se vuelve verdadera.
```angular-html
@defer (hydrate when condition) {
@@ -147,16 +145,11 @@ condition becomes truthy.
}
```
-NOTE: `hydrate when` conditions only trigger when they are the top-most dehydrated `@defer` block. The condition provided for the trigger is
-specified in the parent component, which needs to exist before it can be triggered. If the parent block is dehydrated, that expression will not yet
-be resolvable by Angular.
+NOTA: Las condiciones de `hydrate when` solo se activan cuando son el bloque `@defer` deshidratado más externo. La condición proporcionada para el disparador se especifica en el componente padre, que debe existir antes de que pueda activarse. Si el bloque padre está deshidratado, Angular aún no podrá resolver esa expresión.
### `hydrate never`
-The `hydrate never` allows users to specify that the content in the defer block should remain dehydrated indefinitely, effectively becoming static
-content. Note that this applies to the initial render only. During a subsequent client-side render, a `@defer` block with `hydrate never` would
-still fetch dependencies, as hydration only applies to initial load of server-side rendered content. In the example below, subsequent client-side
-renders would load the `@defer` block dependencies on viewport.
+`hydrate never` permite a los usuarios especificar que el contenido del bloque defer debe permanecer deshidratado indefinidamente, convirtiéndose efectivamente en contenido estático. Ten en cuenta que esto aplica solo a la renderización inicial. Durante una renderización posterior del lado del cliente, un bloque `@defer` con `hydrate never` seguirá obteniendo las dependencias, ya que la hidratación solo aplica a la carga inicial del contenido renderizado del lado del servidor. En el siguiente ejemplo, las renderizaciones posteriores del lado del cliente cargarían las dependencias del bloque `@defer` al entrar en el viewport.
```angular-html
@defer (on viewport; hydrate never) {
@@ -166,11 +159,11 @@ renders would load the `@defer` block dependencies on viewport.
}
```
-NOTE: Using `hydrate never` prevents hydration of the entire nested subtree of a given `@defer` block. No other `hydrate` triggers fire for content nested underneath that block.
+NOTA: Usar `hydrate never` evita la hidratación de todo el subárbol anidado de un bloque `@defer` dado. Ningún otro disparador `hydrate` se activa para el contenido anidado dentro de ese bloque.
-## Hydrate triggers alongside regular triggers
+## Disparadores de hidratación junto con disparadores regulares
-Hydrate triggers are additional triggers that are used alongside regular triggers on a `@defer` block. Hydration is an initial load optimization, and that means hydrate triggers only apply to that initial load. Any subsequent client side render will still use the regular trigger.
+Los disparadores de hidratación son disparadores adicionales que se usan junto con los disparadores regulares en un bloque `@defer`. La hidratación es una optimización de carga inicial, lo que significa que los disparadores de hidratación solo aplican a esa carga inicial. Cualquier renderización posterior del lado del cliente seguirá usando el disparador regular.
```angular-html
@defer (on idle; hydrate on interaction) {
@@ -180,11 +173,11 @@ Hydrate triggers are additional triggers that are used alongside regular trigger
}
```
-In this example, on the initial load, the `hydrate on interaction` applies. Hydration will be triggered on interaction with the ` ` component. On any subsequent page load that is client-side rendered, for example when a user clicks a routerLink that loads a page with this component, the `on idle` will apply.
+En este ejemplo, en la carga inicial se aplica `hydrate on interaction`. La hidratación se activará al interactuar con el componente ` `. En cualquier carga de página posterior que se renderice del lado del cliente, por ejemplo cuando un usuario hace clic en un `routerLink` que carga una página con este componente, se aplicará `on idle`.
-## How does incremental hydration work with nested `@defer` blocks?
+## ¿Cómo funciona la hidratación incremental con bloques `@defer` anidados?
-Angular's component and dependency system is hierarchical, which means hydrating any component requires all of its parents also be hydrated. So if hydration is triggered for a child `@defer` block of a nested set of dehydrated `@defer` blocks, hydration is triggered from the top-most dehydrated `@defer` block down to the triggered child and fire in that order.
+El sistema de componentes y dependencias de Angular es jerárquico, lo que significa que hidratar cualquier componente requiere que todos sus padres también estén hidratados. Por lo tanto, si se activa la hidratación para un bloque `@defer` hijo de un conjunto anidado de bloques `@defer` deshidratados, la hidratación se activa desde el bloque `@defer` deshidratado más externo hasta el hijo activado, y se ejecuta en ese orden.
```angular-html
@defer (hydrate on interaction) {
@@ -199,12 +192,12 @@ Angular's component and dependency system is hierarchical, which means hydrating
}
```
-In the above example, hovering over the nested `@defer` block triggers hydration. The parent `@defer` block with the ` ` hydrates first, then the child `@defer` block with ` ` hydrates after.
+En el ejemplo anterior, al desplazar el mouse sobre el bloque `@defer` anidado se activa la hidratación. El bloque `@defer` padre con ` ` se hidrata primero, luego el bloque `@defer` hijo con ` ` se hidrata después.
-## Constraints
+## Restricciones
-Incremental hydration has the same constraints as full-application hydration, including limits on direct DOM manipulation and requiring valid HTML structure. Visit the [Hydration guide constraints](guide/hydration#constraints) section for more details.
+La hidratación incremental tiene las mismas restricciones que la hidratación completa de la aplicación, incluyendo límites en la manipulación directa del DOM y la necesidad de una estructura HTML válida. Visita la sección de [restricciones de la guía de Hidratación](guide/hydration#restricciones) para más detalles.
-## Do I still need to specify `@placeholder` blocks?
+## ¿Aún necesito especificar bloques `@placeholder`?
-Yes. `@placeholder` block content is not used for incremental hydration, but a `@placeholder` is still necessary for subsequent client-side rendering cases. If your content was not on the route that was part of the initial load, then any navigation to the route that has your `@defer` block content renders like a regular `@defer` block. So the `@placeholder` is rendered in those client-side rendering cases.
+Sí. El contenido del bloque `@placeholder` no se usa para la hidratación incremental, pero un `@placeholder` sigue siendo necesario para los casos de renderización posteriores del lado del cliente. Si tu contenido no estaba en la ruta que fue parte de la carga inicial, entonces cualquier navegación a la ruta que tiene el contenido de tu bloque `@defer` se renderiza como un bloque `@defer` regular. Por lo tanto, el `@placeholder` se renderiza en esos casos de renderización del lado del cliente.
diff --git a/adev-es/src/content/guide/prerendering.en.md b/adev-es/src/content/guide/prerendering.en.md
new file mode 100644
index 0000000..e9b14c1
--- /dev/null
+++ b/adev-es/src/content/guide/prerendering.en.md
@@ -0,0 +1,100 @@
+# Prerendering (SSG)
+
+Prerendering, commonly referred to as Static Site Generation (SSG), represents the method by which pages are rendered to static HTML files during the build process.
+
+Prerendering maintains the same performance benefits of [server-side rendering (SSR)](guide/ssr#why-use-server-side-rendering) but achieves a reduced Time to First Byte (TTFB), ultimately enhancing user experience. The key distinction lies in its approach that pages are served as static content, and there is no request-based rendering.
+
+When the data necessary for server-side rendering remains consistent across all users, the strategy of prerendering emerges as a valuable alternative. Rather than dynamically rendering pages for each user request, prerendering takes a proactive approach by rendering them in advance.
+
+## How to prerender a page
+
+To prerender a static page, add SSR capabilities to your application with the following Angular CLI command:
+
+
+
+ng add @angular/ssr
+
+
+
+
+
+To create an application with prerendering capabilities from the beginning use the [`ng new --ssr`](tools/cli/setup-local) command.
+
+
+
+Once SSR is added, you can generate the static pages by running the build command:
+
+
+
+ng build
+
+
+
+### Build options for prerender
+
+The application builder `prerender` option can be either a Boolean or an Object for more fine-tuned configuration.
+When the option is `false`, no prerendering is done. When it is `true`, all options use the default value. When it is an Object, each option can be individually configured.
+
+| Options | Details | Default Value |
+| :--------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------ |
+| `discoverRoutes` | Whether the builder should process the Angular Router configuration to find all unparameterized routes and prerender them. | `true` |
+| `routesFile` | The path to a file that contains a list of all routes to prerender, separated by newlines. This option is useful if you want to prerender routes with parameterized URLs. | |
+
+
+
+{
+ "projects": {
+ "my-app": {
+ "architect": {
+ "build": {
+ "builder": "@angular-devkit/build-angular:application",
+ "options": {
+ "prerender": {
+ "discoverRoutes": false
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+
+
+### Prerendering parameterized routes
+
+You can prerender parameterized routes using the `routesFile` option. An example of a parameterized route is `product/:id`, where `id` is dynamically provided. To specify these routes, they should be listed in a text file, with each route on a separate line.
+
+For an app with a large number of parameterized routes, consider generating this file using a script before running `ng build`.
+
+
+
+/products/1
+/products/555
+
+
+
+With routes specified in the `routes.txt` file, use the `routesFile` option to configure the builder to prerender the product routes.
+
+
+
+{
+ "projects": {
+ "my-app": {
+ "architect": {
+ "build": {
+ "builder": "@angular-devkit/build-angular:application",
+ "options": {
+ "prerender": {
+ "routesFile": "routes.txt"
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+
+
+This configures `ng build` to prerender `/products/1` and `/products/555` at build time.
diff --git a/adev-es/src/content/guide/prerendering.md b/adev-es/src/content/guide/prerendering.md
index e9b14c1..6fdf76e 100644
--- a/adev-es/src/content/guide/prerendering.md
+++ b/adev-es/src/content/guide/prerendering.md
@@ -1,14 +1,14 @@
-# Prerendering (SSG)
+# Prerenderización (SSG)
-Prerendering, commonly referred to as Static Site Generation (SSG), represents the method by which pages are rendered to static HTML files during the build process.
+La prerenderización, comúnmente conocida como Generación de Sitios Estáticos (SSG), representa el método por el cual las páginas se renderizan como archivos HTML estáticos durante el proceso de compilación.
-Prerendering maintains the same performance benefits of [server-side rendering (SSR)](guide/ssr#why-use-server-side-rendering) but achieves a reduced Time to First Byte (TTFB), ultimately enhancing user experience. The key distinction lies in its approach that pages are served as static content, and there is no request-based rendering.
+La prerenderización mantiene los mismos beneficios de rendimiento del [renderizado del lado del servidor (SSR)](guide/ssr#why-use-server-side-rendering), pero logra un menor Time to First Byte (TTFB), mejorando en última instancia la experiencia del usuario. La distinción clave radica en su enfoque: las páginas se sirven como contenido estático y no hay renderización basada en peticiones.
-When the data necessary for server-side rendering remains consistent across all users, the strategy of prerendering emerges as a valuable alternative. Rather than dynamically rendering pages for each user request, prerendering takes a proactive approach by rendering them in advance.
+Cuando los datos necesarios para la renderización del lado del servidor son consistentes para todos los usuarios, la estrategia de prerenderización surge como una alternativa valiosa. En lugar de renderizar páginas dinámicamente para cada petición del usuario, la prerenderización adopta un enfoque proactivo al renderizarlas de antemano.
-## How to prerender a page
+## Cómo prerenderizar una página
-To prerender a static page, add SSR capabilities to your application with the following Angular CLI command:
+Para prerenderizar una página estática, añade las capacidades de SSR a tu aplicación con el siguiente comando del CLI de Angular:
@@ -18,11 +18,11 @@ ng add @angular/ssr
-To create an application with prerendering capabilities from the beginning use the [`ng new --ssr`](tools/cli/setup-local) command.
+Para crear una aplicación con capacidades de prerenderización desde el principio, usa el comando [`ng new --ssr`](tools/cli/setup-local).
-Once SSR is added, you can generate the static pages by running the build command:
+Una vez que SSR esté añadido, puedes generar las páginas estáticas ejecutando el comando de compilación:
@@ -30,15 +30,14 @@ ng build
-### Build options for prerender
+### Opciones de compilación para prerenderizar
-The application builder `prerender` option can be either a Boolean or an Object for more fine-tuned configuration.
-When the option is `false`, no prerendering is done. When it is `true`, all options use the default value. When it is an Object, each option can be individually configured.
+La opción `prerender` del builder de la aplicación puede ser un booleano o un objeto para una configuración más detallada. Cuando la opción es `false`, no se realiza ninguna prerenderización. Cuando es `true`, todas las opciones usan el valor predeterminado. Cuando es un objeto, cada opción puede configurarse individualmente.
-| Options | Details | Default Value |
-| :--------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------ |
-| `discoverRoutes` | Whether the builder should process the Angular Router configuration to find all unparameterized routes and prerender them. | `true` |
-| `routesFile` | The path to a file that contains a list of all routes to prerender, separated by newlines. This option is useful if you want to prerender routes with parameterized URLs. | |
+| Opciones | Detalles | Valor predeterminado |
+| :--------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------- |
+| `discoverRoutes` | Si el builder debe procesar la configuración del Router de Angular para encontrar todas las rutas sin parámetros y prerenderizarlas. | `true` |
+| `routesFile` | La ruta a un archivo que contiene una lista de todas las rutas a prerenderizar, separadas por saltos de línea. Esta opción es útil si deseas prerenderizar rutas con URLs parametrizadas. | |
@@ -61,11 +60,11 @@ When the option is `false`, no prerendering is done. When it is `true`, all opti
-### Prerendering parameterized routes
+### Prerenderización de rutas parametrizadas
-You can prerender parameterized routes using the `routesFile` option. An example of a parameterized route is `product/:id`, where `id` is dynamically provided. To specify these routes, they should be listed in a text file, with each route on a separate line.
+Puedes prerenderizar rutas parametrizadas usando la opción `routesFile`. Un ejemplo de una ruta parametrizada es `product/:id`, donde `id` se proporciona de forma dinámica. Para especificar estas rutas, deben listarse en un archivo de texto, con cada ruta en una línea separada.
-For an app with a large number of parameterized routes, consider generating this file using a script before running `ng build`.
+Para una aplicación con un gran número de rutas parametrizadas, considera generar este archivo usando un script antes de ejecutar `ng build`.
@@ -74,7 +73,7 @@ For an app with a large number of parameterized routes, consider generating this
-With routes specified in the `routes.txt` file, use the `routesFile` option to configure the builder to prerender the product routes.
+Con las rutas especificadas en el archivo `routes.txt`, usa la opción `routesFile` para configurar el builder y prerenderizar las rutas de productos.
@@ -97,4 +96,4 @@ With routes specified in the `routes.txt` file, use the `routesFile` option to c
-This configures `ng build` to prerender `/products/1` and `/products/555` at build time.
+Esto configura `ng build` para prerenderizar `/products/1` y `/products/555` en tiempo de compilación.
diff --git a/adev-es/src/content/guide/ssr.en.md b/adev-es/src/content/guide/ssr.en.md
new file mode 100644
index 0000000..bd88fbd
--- /dev/null
+++ b/adev-es/src/content/guide/ssr.en.md
@@ -0,0 +1,534 @@
+# Server and hybrid rendering
+
+Angular ships all applications as client-side rendered (CSR) by default. While this approach delivers an initial payload that's lightweight, it introduces trade-offs including slower load times, degraded performance metrics, and higher resource demands since the user's device performs most of the computations. As a result, many applications achieve significant performance improvements by integrating server-side rendering (SSR) into a hybrid rendering strategy.
+
+## What is hybrid rendering?
+
+Hybrid rendering allows developers to leverage the benefits of server-side rendering (SSR), pre-rendering (also known as "static site generation" or SSG) and client-side rendering (CSR) to optimize your Angular application. It gives you fine-grained control over how the different parts of your app are rendered to give your users the best experience possible.
+
+## Setting up hybrid rendering
+
+You can create a **new** project with hybrid rendering by using the server-side rendering flag (i.e., `--ssr`) with the Angular CLI `ng new` command:
+
+```shell
+ng new --ssr
+```
+
+You can also enable hybrid rendering by adding server-side rendering to an existing project with the `ng add` command:
+
+```shell
+ng add @angular/ssr
+```
+
+NOTE: By default, Angular prerenders your entire application and generates a server file. To disable this and create a fully static app, set `outputMode` to `static`. To enable SSR, update the server routes to use `RenderMode.Server`. For more details, see [`Server routing`](#server-routing) and [`Generate a fully static application`](#generate-a-fully-static-application).
+
+## Server routing
+
+### Configuring server routes
+
+You can create a server route config by declaring an array of [`ServerRoute`](api/ssr/ServerRoute 'API reference') objects. This configuration typically lives in a file named `app.routes.server.ts`.
+
+```typescript
+// app.routes.server.ts
+import { RenderMode, ServerRoute } from '@angular/ssr';
+
+export const serverRoutes: ServerRoute[] = [
+ {
+ path: '', // This renders the "/" route on the client (CSR)
+ renderMode: RenderMode.Client,
+ },
+ {
+ path: 'about', // This page is static, so we prerender it (SSG)
+ renderMode: RenderMode.Prerender,
+ },
+ {
+ path: 'profile', // This page requires user-specific data, so we use SSR
+ renderMode: RenderMode.Server,
+ },
+ {
+ path: '**', // All other routes will be rendered on the server (SSR)
+ renderMode: RenderMode.Server,
+ },
+];
+```
+
+You can add this config to your application with [`provideServerRendering`](api/ssr/provideServerRendering 'API reference') using the [`withRoutes`](api/ssr/withRoutes 'API reference') function:
+
+```typescript
+import { provideServerRendering, withRoutes } from '@angular/ssr';
+import { serverRoutes } from './app.routes.server';
+
+// app.config.server.ts
+const serverConfig: ApplicationConfig = {
+ providers: [
+ provideServerRendering(withRoutes(serverRoutes)),
+ // ... other providers ...
+ ]
+};
+```
+
+When using the [App shell pattern](ecosystem/service-workers/app-shell), you must specify the component to be used as the app shell for client-side rendered routes. To do this, use the [`withAppShell`](api/ssr/withAppShell 'API reference') feature:
+
+```typescript
+import { provideServerRendering, withRoutes, withAppShell } from '@angular/ssr';
+import { AppShellComponent } from './app-shell/app-shell.component';
+
+const serverConfig: ApplicationConfig = {
+ providers: [
+ provideServerRendering(
+ withRoutes(serverRoutes),
+ withAppShell(AppShellComponent),
+ ),
+ // ... other providers ...
+ ]
+};
+```
+
+### Rendering modes
+
+The server routing configuration lets you specify how each route in your application should render by setting a [`RenderMode`](api/ssr/RenderMode 'API reference'):
+
+| Rendering mode | Description |
+| ------------------- | ----------------------------------------------------------------------------------------------------------- |
+| **Server (SSR)** | Renders the application on the server for each request, sending a fully populated HTML page to the browser. |
+| **Client (CSR)** | Renders the application in the browser. This is the default Angular behavior. |
+| **Prerender (SSG)** | Prerenders the application at build time, generating static HTML files for each route. |
+
+#### Choosing a rendering mode
+
+Each rendering mode has different benefits and drawbacks. You can choose rendering modes based on the specific needs of your application.
+
+##### Client-side rendering (CSR)
+
+Client-side rendering has the simplest development model, as you can write code that assumes it always runs in a web browser. This lets you use a wide range of client-side libraries that also assume they run in a browser.
+
+Client-side rendering generally has worse performance than other rendering modes, as it must download, parse, and execute your page's JavaScript before the user can see any rendered content. If your page fetches more data from the server as it renders, users also have to wait for those additional requests before they can view the complete content.
+
+If your page is indexed by search crawlers, client-side rendering may negatively affect search engine optimization (SEO), as search crawlers have limits to how much JavaScript they execute when indexing a page.
+
+When client-side rendering, the server does not need to do any work to render a page beyond serving static JavaScript assets. You may consider this factor if server cost is a concern.
+
+Applications that support installable, offline experiences with [service workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can rely on client-side rendering without needing to communicate with a server.
+
+##### Server-side rendering (SSR)
+
+Server-side rendering offers faster page loads than client-side rendering. Instead of waiting for JavaScript to download and run, the server directly renders an HTML document upon receiving a request from the browser. The user experiences only the latency necessary for the server to fetch data and render the requested page. This mode also eliminates the need for additional network requests from the browser, as your code can fetch data during rendering on the server.
+
+Server-side rendering generally has excellent search engine optimization (SEO), as search crawlers receive a fully rendered HTML document.
+
+Server-side rendering requires you to author code that does not strictly depend on browser APIs and limits your selection of JavaScript libraries that assume they run in a browser.
+
+When server-side rendering, your server runs Angular to produce an HTML response for every request which may increase server hosting costs.
+
+##### Build-time prerendering
+
+Prerendering offers faster page loads than both client-side rendering and server-side rendering. Because prerendering creates HTML documents at _build-time_, the server can directly respond to requests with the static HTML document without any additional work.
+
+Prerendering requires that all information necessary to render a page is available at _build-time_. This means that prerendered pages cannot include any data to the specific user loading the page. Prerendering is primarily useful for pages that are the same for all users of your application.
+
+Because prerendering occurs at build-time, it may add significant time to your production builds. Using [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') to produce a large number of HTML documents may affect the total file size of your deployments, and thus lead to slower deployments.
+
+Prerendering generally has excellent search engine optimization (SEO), as search crawlers receive a fully rendered HTML document.
+
+Prerendering requires you to author code that does not strictly depend on browser APIs and limits your selection of JavaScript libraries that assume they run in a browser.
+
+Prerendering incurs extremely little overhead per server request, as your server responds with static HTML documents. Static files are also easily cached by Content Delivery Networks (CDNs), browsers, and intermediate caching layers for even faster subsequent page loads. Fully static sites can also be deployed solely through a CDN or static file server, eliminating the need to maintain a custom server runtime for your application. This enhances scalability by offloading work from an application web server, making it particularly beneficial for high-traffic applications.
+
+NOTE: When using Angular service worker, the first request is server-rendered, but all subsequent requests are handled by the service worker and rendered client-side.
+
+### Setting headers and status codes
+
+You can set custom headers and status codes for individual server routes using the `headers` and `status` properties in the `ServerRoute` configuration.
+
+```typescript
+// app.routes.server.ts
+import { RenderMode, ServerRoute } from '@angular/ssr';
+
+export const serverRoutes: ServerRoute[] = [
+ {
+ path: 'profile',
+ renderMode: RenderMode.Server,
+ headers: {
+ 'X-My-Custom-Header': 'some-value',
+ },
+ status: 201,
+ },
+ // ... other routes
+];
+```
+
+### Redirects
+
+Angular handles redirects specified by the [`redirectTo`](api/router/Route#redirectTo 'API reference') property in route configurations, differently on the server-side.
+
+**Server-Side Rendering (SSR)**
+Redirects are performed using standard HTTP redirects (e.g., 301, 302) within the server-side rendering process.
+
+**Prerendering (SSG)**
+Redirects are implemented as "soft redirects" using [` `](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#refresh) tags in the prerendered HTML.
+
+### Customizing build-time prerendering (SSG)
+
+When using [`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference'), you can specify several configuration options to customize the prerendering and serving process.
+
+#### Parameterized routes
+
+For each route with [`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference'), you can specify a [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') function. This function lets you control which specific parameters produce separate prerendered documents.
+
+The [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') function returns a `Promise` that resolves to an array of objects. Each object is a key-value map of route parameter name to value. For example, if you define a route like `post/:id`, `getPrerenderParams ` could return the array `[{id: 123}, {id: 456}]`, and thus render separate documents for `post/123` and `post/456`.
+
+The body of [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') can use Angular's [`inject`](api/core/inject 'API reference') function to inject dependencies and perform any work to determine which routes to prerender. This typically includes making requests to fetch data to construct the array of parameter values.
+
+You can also use this function with catch-all routes (e.g., `/**`), where the parameter name will be `"**"` and the return value will be the segments of the path, such as `foo/bar`. These can be combined with other parameters (e.g., `/post/:id/**`) to handle more complex route configuration.
+
+```ts
+// app.routes.server.ts
+import { RenderMode, ServerRoute } from '@angular/ssr';
+
+export const serverRoutes: ServerRoute[] = [
+ {
+ path: 'post/:id',
+ renderMode: RenderMode.Prerender,
+ async getPrerenderParams() {
+ const dataService = inject(PostService);
+ const ids = await dataService.getIds(); // Assuming this returns ['1', '2', '3']
+
+ return ids.map(id => ({ id })); // Generates paths like: /post/1, /post/2, /post/3
+ },
+ },
+ {
+ path: 'post/:id/**',
+ renderMode: RenderMode.Prerender,
+ async getPrerenderParams() {
+ return [
+ { id: '1', '**': 'foo/3' },
+ { id: '2', '**': 'bar/4' },
+ ]; // Generates paths like: /post/1/foo/3, /post/2/bar/4
+ },
+ },
+];
+```
+
+Because [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') exclusively applies to [`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference'), this function always runs at _build-time_. `getPrerenderParams` must not rely on any browser-specific or server-specific APIs for data.
+
+IMPORTANT: When using [`inject`](api/core/inject 'API reference') inside `getPrerenderParams`, please remember that `inject` must be used synchronously. It cannot be invoked within asynchronous callbacks or following any `await` statements. For more information, refer to `runInInjectionContext`.
+
+#### Fallback strategies
+
+When using [`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference') mode, you can specify a fallback strategy to handle requests for paths that haven't been prerendered.
+
+The available fallback strategies are:
+
+- **Server:** Falls back to server-side rendering. This is the **default** behavior if no `fallback` property is specified.
+- **Client:** Falls back to client-side rendering.
+- **None:** No fallback. Angular will not handle requests for paths that are not prerendered.
+
+```ts
+// app.routes.server.ts
+import { RenderMode, PrerenderFallback, ServerRoute } from '@angular/ssr';
+
+export const serverRoutes: ServerRoute[] = [
+ {
+ path: 'post/:id',
+ renderMode: RenderMode.Prerender,
+ fallback: PrerenderFallback.Client, // Fallback to CSR if not prerendered
+ async getPrerenderParams() {
+ // This function returns an array of objects representing prerendered posts at the paths:
+ // `/post/1`, `/post/2`, and `/post/3`.
+ // The path `/post/4` will utilize the fallback behavior if it's requested.
+ return [{ id: 1 }, { id: 2 }, { id: 3 }];
+ },
+ },
+];
+```
+
+## Authoring server-compatible components
+
+Some common browser APIs and capabilities might not be available on the server. Applications cannot make use of browser-specific global objects like `window`, `document`, `navigator`, or `location` as well as certain properties of `HTMLElement`.
+
+In general, code which relies on browser-specific symbols should only be executed in the browser, not on the server. This can be enforced through the `afterEveryRender` and `afterNextRender` lifecycle hooks. These are only executed on the browser and skipped on the server.
+
+```angular-ts
+import { Component, viewChild, afterNextRender } from '@angular/core';
+
+@Component({
+ selector: 'my-cmp',
+ template: `{{ ... }} `,
+})
+export class MyComponent {
+ contentRef = viewChild.required('content');
+
+ constructor() {
+ afterNextRender(() => {
+ // Safe to check `scrollHeight` because this will only run in the browser, not the server.
+ console.log('content height: ' + this.contentRef().nativeElement.scrollHeight);
+ });
+ }
+}
+```
+
+## Setting providers on the server
+
+On the server side, top level provider values are set once when the application code is initially parsed and evaluated.
+This means that providers configured with `useValue` will keep their value across multiple requests, until the server application is restarted.
+
+If you want to generate a new value for each request, use a factory provider with `useFactory`. The factory function will run for every incoming request, ensuring that a new value is created and assigned to the token each time.
+
+## Accessing Document via DI
+
+When working with server-side rendering, you should avoid directly referencing browser-specific globals like `document`. Instead, use the [`DOCUMENT`](api/core/DOCUMENT) token to access the document object in a platform-agnostic way.
+
+```ts
+import { Injectable, inject, DOCUMENT } from '@angular/core';
+
+@Injectable({ providedIn: 'root' })
+export class CanonicalLinkService {
+ private readonly document = inject(DOCUMENT);
+
+ // During server rendering, inject a tag
+ // so the generated HTML includes the correct canonical URL
+ setCanonical(href: string): void {
+ const link = this.document.createElement('link');
+ link.rel = 'canonical';
+ link.href = href;
+ this.document.head.appendChild(link);
+ }
+}
+
+```
+
+HELPFUL: For managing meta tags, Angular provides the `Meta` service.
+
+## Accessing Request and Response via DI
+
+The `@angular/core` package provides several tokens for interacting with the server-side rendering environment. These tokens give you access to crucial information and objects within your Angular application during SSR.
+
+- **[`REQUEST`](api/core/REQUEST 'API reference'):** Provides access to the current request object, which is of type [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) from the Web API. This allows you to access headers, cookies, and other request information.
+- **[`RESPONSE_INIT`](api/core/RESPONSE_INIT 'API reference'):** Provides access to the response initialization options, which is of type [`ResponseInit`](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#parameters) from the Web API. This allows you to set headers and the status code for the response dynamically. Use this token to set headers or status codes that need to be determined at runtime.
+- **[`REQUEST_CONTEXT`](api/core/REQUEST_CONTEXT 'API reference'):** Provides access to additional context related to the current request. This context can be passed as the second parameter of the [`handle`](api/ssr/AngularAppEngine#handle 'API reference') function. Typically, this is used to provide additional request-related information that is not part of the standard Web API.
+
+```angular-ts
+import { inject, REQUEST } from '@angular/core';
+
+@Component({
+ selector: 'app-my-component',
+ template: `My Component `,
+})
+export class MyComponent {
+ constructor() {
+ const request = inject(REQUEST);
+ console.log(request?.url);
+ }
+}
+```
+
+IMPORTANT: The above tokens will be `null` in the following scenarios:
+
+- During the build processes.
+- When the application is rendered in the browser (CSR).
+- When performing static site generation (SSG).
+- During route extraction in development (at the time of the request).
+
+## Generate a fully static application
+
+By default, Angular prerenders your entire application and generates a server file for handling requests. This allows your app to serve pre-rendered content to users. However, if you prefer a fully static site without a server, you can opt out of this behavior by setting the `outputMode` to `static` in your `angular.json` configuration file.
+
+When `outputMode` is set to `static`, Angular generates pre-rendered HTML files for each route at build time, but it does not generate a server file or require a Node.js server to serve the app. This is useful for deploying to static hosting providers where a backend server is not needed.
+
+To configure this, update your `angular.json` file as follows:
+
+```json
+{
+ "projects": {
+ "your-app": {
+ "architect": {
+ "build": {
+ "options": {
+ "outputMode": "static"
+ }
+ }
+ }
+ }
+ }
+}
+```
+
+## Caching data when using HttpClient
+
+`HttpClient` caches outgoing network requests when running on the server. This information is serialized and transferred to the browser as part of the initial HTML sent from the server. In the browser, `HttpClient` checks whether it has data in the cache and if so, reuses it instead of making a new HTTP request during initial application rendering. `HttpClient` stops using the cache once an application becomes [stable](api/core/ApplicationRef#isStable) while running in a browser.
+
+### Configuring the caching options
+
+You can customize how Angular caches HTTP responses during server‑side rendering (SSR) and reuses them during hydration by configuring `HttpTransferCacheOptions`.
+This configuration is provided globally using `withHttpTransferCacheOptions` inside `provideClientHydration()`.
+
+By default, `HttpClient` caches all `HEAD` and `GET` requests which don't contain `Authorization` or `Proxy-Authorization` headers. You can override those settings by using `withHttpTransferCacheOptions` to the hydration configuration.
+
+```ts
+import { bootstrapApplication } from '@angular/platform-browser';
+import { provideClientHydration, withHttpTransferCacheOptions } from '@angular/platform-browser';
+
+bootstrapApplication(AppComponent, {
+ providers: [
+ provideClientHydration(
+ withHttpTransferCacheOptions({
+ includeHeaders: ['ETag', 'Cache-Control'],
+ filter: (req) => !req.url.includes('/api/profile'),
+ includePostRequests: true,
+ includeRequestsWithAuthHeaders: false,
+ }),
+ ),
+ ],
+});
+```
+
+---
+
+### `includeHeaders`
+
+Specifies which headers from the server response should be included in cached entries.
+No headers are included by default.
+
+```ts
+withHttpTransferCacheOptions({
+ includeHeaders: ['ETag', 'Cache-Control'],
+});
+```
+
+IMPORTANT: Avoid including sensitive headers like authentication tokens. These can leak user‑specific data between requests.
+
+---
+
+### `includePostRequests`
+
+By default, only `GET` and `HEAD` requests are cached.
+You can enable caching for `POST` requests when they are used as read operations such as GraphQL queries.
+
+```ts
+withHttpTransferCacheOptions({
+ includePostRequests: true,
+});
+```
+
+Use this only when `POST` requests are **idempotent** and safe to reuse between server and client renders.
+
+---
+
+### `includeRequestsWithAuthHeaders`
+
+Determines whether requests containing `Authorization` or `Proxy‑Authorization` headers are eligible for caching.
+By default, these are excluded to prevent caching user‑specific responses.
+
+```ts
+withHttpTransferCacheOptions({
+ includeRequestsWithAuthHeaders: true,
+});
+```
+
+Enable only when authentication headers do **not** affect the response content (for example, public tokens for analytics APIs).
+
+### Per‑request overrides
+
+You can override caching behavior for a specific request using the `transferCache` request option.
+
+```ts
+// Include specific headers for this request
+http.get('/api/profile', { transferCache: { includeHeaders: ['CustomHeader'] } });
+```
+
+### Disabling caching
+
+You can disable HTTP caching of requests sent from the server either globally or individually.
+
+#### Globally
+
+To disable caching for all requests in your application, use the `withNoHttpTransferCache` feature:
+
+```ts
+import { bootstrapApplication, provideClientHydration, withNoHttpTransferCache } from '@angular/platform-browser';
+
+bootstrapApplication(AppComponent, {
+ providers: [
+ provideClientHydration(withNoHttpTransferCache())
+ ]
+});
+```
+
+#### `filter`
+
+You can also selectively disable caching for certain requests using the [`filter`](api/common/http/HttpTransferCacheOptions) option in `withHttpTransferCacheOptions`. For example, you can disable caching for a specific API endpoint:
+
+```ts
+import { bootstrapApplication, provideClientHydration, withHttpTransferCacheOptions } from '@angular/platform-browser';
+
+bootstrapApplication(AppComponent, {
+ providers: [
+ provideClientHydration(withHttpTransferCacheOptions({
+ filter: (req) => !req.url.includes('/api/sensitive-data')
+ }))
+ ]
+});
+```
+
+Use this option to exclude endpoints with user‑specific or dynamic data (for example `/api/profile`).
+
+#### Individually
+
+To disable caching for an individual request, you can specify the [`transferCache`](api/common/http/HttpRequest#transferCache) option in an `HttpRequest`.
+
+```ts
+httpClient.get('/api/sensitive-data', { transferCache: false });
+```
+
+## Configuring a server
+
+### Node.js
+
+The `@angular/ssr/node` extends `@angular/ssr` specifically for Node.js environments. It provides APIs that make it easier to implement server-side rendering within your Node.js application. For a complete list of functions and usage examples, refer to the [`@angular/ssr/node` API reference](api/ssr/node/AngularNodeAppEngine) API reference.
+
+```ts
+// server.ts
+import { AngularNodeAppEngine, createNodeRequestHandler, writeResponseToNodeResponse } from '@angular/ssr/node';
+import express from 'express';
+
+const app = express();
+const angularApp = new AngularNodeAppEngine();
+
+app.use('*', (req, res, next) => {
+ angularApp
+ .handle(req)
+ .then(response => {
+ if (response) {
+ writeResponseToNodeResponse(response, res);
+ } else {
+ next(); // Pass control to the next middleware
+ }
+ })
+ .catch(next);
+});
+
+/**
+ * The request handler used by the Angular CLI (dev-server and during build).
+ */
+export const reqHandler = createNodeRequestHandler(app);
+```
+
+### Non-Node.js
+
+The `@angular/ssr` provides essential APIs for server-side rendering your Angular application on platforms other than Node.js. It leverages the standard [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) and [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) objects from the Web API, enabling you to integrate Angular SSR into various server environments. For detailed information and examples, refer to the [`@angular/ssr` API reference](api/ssr/AngularAppEngine).
+
+```ts
+// server.ts
+import { AngularAppEngine, createRequestHandler } from '@angular/ssr';
+
+const angularApp = new AngularAppEngine();
+
+/**
+ * This is a request handler used by the Angular CLI (dev-server and during build).
+ */
+export const reqHandler = createRequestHandler(async (req: Request) => {
+ const res: Response|null = await angularApp.render(req);
+
+ // ...
+});
+```
diff --git a/adev-es/src/content/guide/ssr.md b/adev-es/src/content/guide/ssr.md
index bd88fbd..34c444b 100644
--- a/adev-es/src/content/guide/ssr.md
+++ b/adev-es/src/content/guide/ssr.md
@@ -1,32 +1,32 @@
-# Server and hybrid rendering
+# Renderización en el servidor y renderización híbrida
-Angular ships all applications as client-side rendered (CSR) by default. While this approach delivers an initial payload that's lightweight, it introduces trade-offs including slower load times, degraded performance metrics, and higher resource demands since the user's device performs most of the computations. As a result, many applications achieve significant performance improvements by integrating server-side rendering (SSR) into a hybrid rendering strategy.
+Angular distribuye todas las aplicaciones con renderización del lado del cliente (CSR) de forma predeterminada. Si bien este enfoque proporciona una carga inicial liviana, introduce compromisos que incluyen tiempos de carga más lentos, métricas de rendimiento degradadas y mayores demandas de recursos, ya que el dispositivo del usuario realiza la mayor parte de los cálculos. Como resultado, muchas aplicaciones logran mejoras significativas de rendimiento al integrar la renderización del lado del servidor (SSR) en una estrategia de renderización híbrida.
-## What is hybrid rendering?
+## ¿Qué es la renderización híbrida?
-Hybrid rendering allows developers to leverage the benefits of server-side rendering (SSR), pre-rendering (also known as "static site generation" or SSG) and client-side rendering (CSR) to optimize your Angular application. It gives you fine-grained control over how the different parts of your app are rendered to give your users the best experience possible.
+La renderización híbrida permite a los desarrolladores aprovechar los beneficios de la renderización del lado del servidor (SSR), el pre-renderizado (también conocido como "generación de sitios estáticos" o SSG) y la renderización del lado del cliente (CSR) para optimizar tu aplicación Angular. Te brinda un control detallado sobre cómo se renderizan las diferentes partes de tu aplicación para ofrecer a tus usuarios la mejor experiencia posible.
-## Setting up hybrid rendering
+## Configurando la renderización híbrida
-You can create a **new** project with hybrid rendering by using the server-side rendering flag (i.e., `--ssr`) with the Angular CLI `ng new` command:
+Puedes crear un proyecto **nuevo** con renderización híbrida utilizando el flag de renderización del lado del servidor (es decir, `--ssr`) con el comando `ng new` de Angular CLI:
```shell
ng new --ssr
```
-You can also enable hybrid rendering by adding server-side rendering to an existing project with the `ng add` command:
+También puedes habilitar la renderización híbrida añadiendo la renderización del lado del servidor a un proyecto existente con el comando `ng add`:
```shell
ng add @angular/ssr
```
-NOTE: By default, Angular prerenders your entire application and generates a server file. To disable this and create a fully static app, set `outputMode` to `static`. To enable SSR, update the server routes to use `RenderMode.Server`. For more details, see [`Server routing`](#server-routing) and [`Generate a fully static application`](#generate-a-fully-static-application).
+NOTA: De forma predeterminada, Angular pre-renderiza toda tu aplicación y genera un archivo de servidor. Para deshabilitar esto y crear una aplicación completamente estática, establece `outputMode` en `static`. Para habilitar SSR, actualiza las rutas del servidor para usar `RenderMode.Server`. Para más detalles, consulta [`Enrutamiento en el servidor`](#enrutamiento-en-el-servidor) y [`Generar una aplicación completamente estática`](#generar-una-aplicación-completamente-estática).
-## Server routing
+## Enrutamiento en el servidor
-### Configuring server routes
+### Configurando rutas del servidor
-You can create a server route config by declaring an array of [`ServerRoute`](api/ssr/ServerRoute 'API reference') objects. This configuration typically lives in a file named `app.routes.server.ts`.
+Puedes crear una configuración de rutas del servidor declarando un array de objetos [`ServerRoute`](api/ssr/ServerRoute 'API reference'). Esta configuración generalmente se encuentra en un archivo llamado `app.routes.server.ts`.
```typescript
// app.routes.server.ts
@@ -34,25 +34,25 @@ import { RenderMode, ServerRoute } from '@angular/ssr';
export const serverRoutes: ServerRoute[] = [
{
- path: '', // This renders the "/" route on the client (CSR)
+ path: '', // Esta ruta renderiza "/" en el cliente (CSR)
renderMode: RenderMode.Client,
},
{
- path: 'about', // This page is static, so we prerender it (SSG)
+ path: 'about', // Esta página es estática, por lo que la pre-renderizamos (SSG)
renderMode: RenderMode.Prerender,
},
{
- path: 'profile', // This page requires user-specific data, so we use SSR
+ path: 'profile', // Esta página requiere datos específicos del usuario, por lo que usamos SSR
renderMode: RenderMode.Server,
},
{
- path: '**', // All other routes will be rendered on the server (SSR)
+ path: '**', // Todas las demás rutas se renderizarán en el servidor (SSR)
renderMode: RenderMode.Server,
},
];
```
-You can add this config to your application with [`provideServerRendering`](api/ssr/provideServerRendering 'API reference') using the [`withRoutes`](api/ssr/withRoutes 'API reference') function:
+Puedes añadir esta configuración a tu aplicación con [`provideServerRendering`](api/ssr/provideServerRendering 'API reference') usando la función [`withRoutes`](api/ssr/withRoutes 'API reference'):
```typescript
import { provideServerRendering, withRoutes } from '@angular/ssr';
@@ -62,12 +62,12 @@ import { serverRoutes } from './app.routes.server';
const serverConfig: ApplicationConfig = {
providers: [
provideServerRendering(withRoutes(serverRoutes)),
- // ... other providers ...
+ // ... otros proveedores ...
]
};
```
-When using the [App shell pattern](ecosystem/service-workers/app-shell), you must specify the component to be used as the app shell for client-side rendered routes. To do this, use the [`withAppShell`](api/ssr/withAppShell 'API reference') feature:
+Cuando se usa el [patrón App shell](ecosystem/service-workers/app-shell), debes especificar el componente que se usará como app shell para las rutas renderizadas del lado del cliente. Para hacerlo, usa la característica [`withAppShell`](api/ssr/withAppShell 'API reference'):
```typescript
import { provideServerRendering, withRoutes, withAppShell } from '@angular/ssr';
@@ -79,66 +79,66 @@ const serverConfig: ApplicationConfig = {
withRoutes(serverRoutes),
withAppShell(AppShellComponent),
),
- // ... other providers ...
+ // ... otros proveedores ...
]
};
```
-### Rendering modes
+### Modos de renderización
-The server routing configuration lets you specify how each route in your application should render by setting a [`RenderMode`](api/ssr/RenderMode 'API reference'):
+La configuración de enrutamiento del servidor te permite especificar cómo debe renderizarse cada ruta en tu aplicación estableciendo un [`RenderMode`](api/ssr/RenderMode 'API reference'):
-| Rendering mode | Description |
-| ------------------- | ----------------------------------------------------------------------------------------------------------- |
-| **Server (SSR)** | Renders the application on the server for each request, sending a fully populated HTML page to the browser. |
-| **Client (CSR)** | Renders the application in the browser. This is the default Angular behavior. |
-| **Prerender (SSG)** | Prerenders the application at build time, generating static HTML files for each route. |
+| Modo de renderización | Descripción |
+| --------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
+| **Server (SSR)** | Renderiza la aplicación en el servidor para cada petición, enviando una página HTML completamente poblada al navegador. |
+| **Client (CSR)** | Renderiza la aplicación en el navegador. Este es el comportamiento predeterminado en Angular. |
+| **Prerender (SSG)** | Pre-renderiza la aplicación en tiempo de compilación, generando archivos HTML estáticos para cada ruta. |
-#### Choosing a rendering mode
+#### Eligiendo un modo de renderización
-Each rendering mode has different benefits and drawbacks. You can choose rendering modes based on the specific needs of your application.
+Cada modo de renderización tiene diferentes beneficios e inconvenientes. Puedes elegir modos de renderización según las necesidades específicas de tu aplicación.
-##### Client-side rendering (CSR)
+##### Renderización del lado del cliente (CSR)
-Client-side rendering has the simplest development model, as you can write code that assumes it always runs in a web browser. This lets you use a wide range of client-side libraries that also assume they run in a browser.
+La renderización del lado del cliente tiene el modelo de desarrollo más sencillo, ya que puedes escribir código asumiendo que siempre se ejecuta en un navegador web. Esto te permite usar una amplia variedad de bibliotecas del lado del cliente que también asumen que se ejecutan en un navegador.
-Client-side rendering generally has worse performance than other rendering modes, as it must download, parse, and execute your page's JavaScript before the user can see any rendered content. If your page fetches more data from the server as it renders, users also have to wait for those additional requests before they can view the complete content.
+La renderización del lado del cliente generalmente tiene peor rendimiento que otros modos de renderización, ya que debe descargar, parsear y ejecutar el JavaScript de tu página antes de que el usuario pueda ver cualquier contenido renderizado. Si tu página obtiene más datos del servidor mientras se renderiza, los usuarios también deben esperar esas peticiones adicionales antes de poder ver el contenido completo.
-If your page is indexed by search crawlers, client-side rendering may negatively affect search engine optimization (SEO), as search crawlers have limits to how much JavaScript they execute when indexing a page.
+Si tu página es indexada por rastreadores de búsqueda, la renderización del lado del cliente puede afectar negativamente la optimización para motores de búsqueda (SEO), ya que los rastreadores tienen límites en la cantidad de JavaScript que ejecutan al indexar una página.
-When client-side rendering, the server does not need to do any work to render a page beyond serving static JavaScript assets. You may consider this factor if server cost is a concern.
+Cuando se usa renderización del lado del cliente, el servidor no necesita hacer ningún trabajo para renderizar una página más allá de servir recursos estáticos de JavaScript. Puedes considerar este factor si el costo del servidor es una preocupación.
-Applications that support installable, offline experiences with [service workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) can rely on client-side rendering without needing to communicate with a server.
+Las aplicaciones que admiten experiencias instalables y sin conexión con [service workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API) pueden depender de la renderización del lado del cliente sin necesidad de comunicarse con un servidor.
-##### Server-side rendering (SSR)
+##### Renderización del lado del servidor (SSR)
-Server-side rendering offers faster page loads than client-side rendering. Instead of waiting for JavaScript to download and run, the server directly renders an HTML document upon receiving a request from the browser. The user experiences only the latency necessary for the server to fetch data and render the requested page. This mode also eliminates the need for additional network requests from the browser, as your code can fetch data during rendering on the server.
+La renderización del lado del servidor ofrece cargas de página más rápidas que la renderización del lado del cliente. En lugar de esperar a que JavaScript se descargue y ejecute, el servidor renderiza directamente un documento HTML al recibir una petición del navegador. El usuario experimenta únicamente la latencia necesaria para que el servidor obtenga datos y renderice la página solicitada. Este modo también elimina la necesidad de peticiones de red adicionales desde el navegador, ya que tu código puede obtener datos durante la renderización en el servidor.
-Server-side rendering generally has excellent search engine optimization (SEO), as search crawlers receive a fully rendered HTML document.
+La renderización del lado del servidor generalmente tiene una excelente optimización para motores de búsqueda (SEO), ya que los rastreadores de búsqueda reciben un documento HTML completamente renderizado.
-Server-side rendering requires you to author code that does not strictly depend on browser APIs and limits your selection of JavaScript libraries that assume they run in a browser.
+La renderización del lado del servidor requiere que escribas código que no dependa estrictamente de las APIs del navegador y limita tu selección de bibliotecas JavaScript que asumen que se ejecutan en un navegador.
-When server-side rendering, your server runs Angular to produce an HTML response for every request which may increase server hosting costs.
+Cuando se usa renderización del lado del servidor, tu servidor ejecuta Angular para producir una respuesta HTML por cada petición, lo que puede aumentar los costos de alojamiento del servidor.
-##### Build-time prerendering
+##### Pre-renderizado en tiempo de compilación
-Prerendering offers faster page loads than both client-side rendering and server-side rendering. Because prerendering creates HTML documents at _build-time_, the server can directly respond to requests with the static HTML document without any additional work.
+El pre-renderizado ofrece cargas de página más rápidas que tanto la renderización del lado del cliente como la renderización del lado del servidor. Debido a que el pre-renderizado crea documentos HTML en _tiempo de compilación_, el servidor puede responder directamente a las peticiones con el documento HTML estático sin ningún trabajo adicional.
-Prerendering requires that all information necessary to render a page is available at _build-time_. This means that prerendered pages cannot include any data to the specific user loading the page. Prerendering is primarily useful for pages that are the same for all users of your application.
+El pre-renderizado requiere que toda la información necesaria para renderizar una página esté disponible en _tiempo de compilación_. Esto significa que las páginas pre-renderizadas no pueden incluir datos específicos del usuario que está cargando la página. El pre-renderizado es principalmente útil para páginas que son iguales para todos los usuarios de tu aplicación.
-Because prerendering occurs at build-time, it may add significant time to your production builds. Using [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') to produce a large number of HTML documents may affect the total file size of your deployments, and thus lead to slower deployments.
+Debido a que el pre-renderizado ocurre en tiempo de compilación, puede añadir un tiempo significativo a tus compilaciones de producción. Usar [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') para producir una gran cantidad de documentos HTML puede afectar el tamaño total de archivos de tus despliegues y, por lo tanto, provocar despliegues más lentos.
-Prerendering generally has excellent search engine optimization (SEO), as search crawlers receive a fully rendered HTML document.
+El pre-renderizado generalmente tiene una excelente optimización para motores de búsqueda (SEO), ya que los rastreadores de búsqueda reciben un documento HTML completamente renderizado.
-Prerendering requires you to author code that does not strictly depend on browser APIs and limits your selection of JavaScript libraries that assume they run in a browser.
+El pre-renderizado requiere que escribas código que no dependa estrictamente de las APIs del navegador y limita tu selección de bibliotecas JavaScript que asumen que se ejecutan en un navegador.
-Prerendering incurs extremely little overhead per server request, as your server responds with static HTML documents. Static files are also easily cached by Content Delivery Networks (CDNs), browsers, and intermediate caching layers for even faster subsequent page loads. Fully static sites can also be deployed solely through a CDN or static file server, eliminating the need to maintain a custom server runtime for your application. This enhances scalability by offloading work from an application web server, making it particularly beneficial for high-traffic applications.
+El pre-renderizado incurre en una sobrecarga mínima por petición al servidor, ya que tu servidor responde con documentos HTML estáticos. Los archivos estáticos también se pueden almacenar en caché fácilmente mediante redes de distribución de contenido (CDN), navegadores y capas intermedias de caché para cargas de página subsiguientes aún más rápidas. Los sitios completamente estáticos también pueden desplegarse únicamente a través de una CDN o un servidor de archivos estáticos, eliminando la necesidad de mantener un tiempo de ejecución de servidor personalizado para tu aplicación. Esto mejora la escalabilidad al descargar trabajo de un servidor web de aplicaciones, lo que lo hace especialmente beneficioso para aplicaciones de alto tráfico.
-NOTE: When using Angular service worker, the first request is server-rendered, but all subsequent requests are handled by the service worker and rendered client-side.
+NOTA: Cuando se usa el service worker de Angular, la primera petición se renderiza en el servidor, pero todas las peticiones subsiguientes son gestionadas por el service worker y renderizadas del lado del cliente.
-### Setting headers and status codes
+### Configurando encabezados y códigos de estado
-You can set custom headers and status codes for individual server routes using the `headers` and `status` properties in the `ServerRoute` configuration.
+Puedes establecer encabezados y códigos de estado personalizados para rutas individuales del servidor usando las propiedades `headers` y `status` en la configuración de `ServerRoute`.
```typescript
// app.routes.server.ts
@@ -153,33 +153,33 @@ export const serverRoutes: ServerRoute[] = [
},
status: 201,
},
- // ... other routes
+ // ... otras rutas
];
```
-### Redirects
+### Redirecciones
-Angular handles redirects specified by the [`redirectTo`](api/router/Route#redirectTo 'API reference') property in route configurations, differently on the server-side.
+Angular maneja las redirecciones especificadas por la propiedad [`redirectTo`](api/router/Route#redirectTo 'API reference') en las configuraciones de rutas de manera diferente en el lado del servidor.
-**Server-Side Rendering (SSR)**
-Redirects are performed using standard HTTP redirects (e.g., 301, 302) within the server-side rendering process.
+**Renderización del lado del servidor (SSR)**
+Las redirecciones se realizan mediante redirecciones HTTP estándar (por ejemplo, 301, 302) dentro del proceso de renderización del lado del servidor.
-**Prerendering (SSG)**
-Redirects are implemented as "soft redirects" using [` `](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#refresh) tags in the prerendered HTML.
+**Pre-renderizado (SSG)**
+Las redirecciones se implementan como "redirecciones suaves" usando etiquetas [` `](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta#refresh) en el HTML pre-renderizado.
-### Customizing build-time prerendering (SSG)
+### Personalizando el pre-renderizado en tiempo de compilación (SSG)
-When using [`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference'), you can specify several configuration options to customize the prerendering and serving process.
+Cuando se usa [`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference'), puedes especificar varias opciones de configuración para personalizar el proceso de pre-renderizado y servicio.
-#### Parameterized routes
+#### Rutas parametrizadas
-For each route with [`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference'), you can specify a [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') function. This function lets you control which specific parameters produce separate prerendered documents.
+Para cada ruta con [`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference'), puedes especificar una función [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference'). Esta función te permite controlar qué parámetros específicos producen documentos pre-renderizados separados.
-The [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') function returns a `Promise` that resolves to an array of objects. Each object is a key-value map of route parameter name to value. For example, if you define a route like `post/:id`, `getPrerenderParams ` could return the array `[{id: 123}, {id: 456}]`, and thus render separate documents for `post/123` and `post/456`.
+La función [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') retorna una `Promise` que se resuelve en un array de objetos. Cada objeto es un mapa clave-valor del nombre del parámetro de ruta a su valor. Por ejemplo, si defines una ruta como `post/:id`, `getPrerenderParams` podría retornar el array `[{id: 123}, {id: 456}]`, y así renderizar documentos separados para `post/123` y `post/456`.
-The body of [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') can use Angular's [`inject`](api/core/inject 'API reference') function to inject dependencies and perform any work to determine which routes to prerender. This typically includes making requests to fetch data to construct the array of parameter values.
+El cuerpo de [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') puede usar la función [`inject`](api/core/inject 'API reference') de Angular para inyectar dependencias y realizar cualquier trabajo para determinar qué rutas pre-renderizar. Esto generalmente incluye hacer peticiones para obtener datos y construir el array de valores de parámetros.
-You can also use this function with catch-all routes (e.g., `/**`), where the parameter name will be `"**"` and the return value will be the segments of the path, such as `foo/bar`. These can be combined with other parameters (e.g., `/post/:id/**`) to handle more complex route configuration.
+También puedes usar esta función con rutas catch-all (por ejemplo, `/**`), donde el nombre del parámetro será `"**"` y el valor de retorno serán los segmentos de la ruta, como `foo/bar`. Estos pueden combinarse con otros parámetros (por ejemplo, `/post/:id/**`) para manejar configuraciones de rutas más complejas.
```ts
// app.routes.server.ts
@@ -191,9 +191,9 @@ export const serverRoutes: ServerRoute[] = [
renderMode: RenderMode.Prerender,
async getPrerenderParams() {
const dataService = inject(PostService);
- const ids = await dataService.getIds(); // Assuming this returns ['1', '2', '3']
+ const ids = await dataService.getIds(); // Asumiendo que esto retorna ['1', '2', '3']
- return ids.map(id => ({ id })); // Generates paths like: /post/1, /post/2, /post/3
+ return ids.map(id => ({ id })); // Genera rutas como: /post/1, /post/2, /post/3
},
},
{
@@ -203,25 +203,25 @@ export const serverRoutes: ServerRoute[] = [
return [
{ id: '1', '**': 'foo/3' },
{ id: '2', '**': 'bar/4' },
- ]; // Generates paths like: /post/1/foo/3, /post/2/bar/4
+ ]; // Genera rutas como: /post/1/foo/3, /post/2/bar/4
},
},
];
```
-Because [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') exclusively applies to [`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference'), this function always runs at _build-time_. `getPrerenderParams` must not rely on any browser-specific or server-specific APIs for data.
+Dado que [`getPrerenderParams`](api/ssr/ServerRoutePrerenderWithParams#getPrerenderParams 'API reference') aplica exclusivamente a [`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference'), esta función siempre se ejecuta en _tiempo de compilación_. `getPrerenderParams` no debe depender de ninguna API específica del navegador o del servidor para obtener datos.
-IMPORTANT: When using [`inject`](api/core/inject 'API reference') inside `getPrerenderParams`, please remember that `inject` must be used synchronously. It cannot be invoked within asynchronous callbacks or following any `await` statements. For more information, refer to `runInInjectionContext`.
+IMPORTANTE: Cuando se use [`inject`](api/core/inject 'API reference') dentro de `getPrerenderParams`, recuerda que `inject` debe usarse de forma síncrona. No puede invocarse dentro de callbacks asíncronos ni después de ninguna instrucción `await`. Para más información, consulta `runInInjectionContext`.
-#### Fallback strategies
+#### Estrategias de alternativa
-When using [`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference') mode, you can specify a fallback strategy to handle requests for paths that haven't been prerendered.
+Cuando se usa el modo [`RenderMode.Prerender`](api/ssr/RenderMode#Prerender 'API reference'), puedes especificar una estrategia de alternativa para gestionar las peticiones de rutas que no han sido pre-renderizadas.
-The available fallback strategies are:
+Las estrategias de alternativa disponibles son:
-- **Server:** Falls back to server-side rendering. This is the **default** behavior if no `fallback` property is specified.
-- **Client:** Falls back to client-side rendering.
-- **None:** No fallback. Angular will not handle requests for paths that are not prerendered.
+- **Server:** Recurre a la renderización del lado del servidor. Este es el comportamiento **predeterminado** si no se especifica ninguna propiedad `fallback`.
+- **Client:** Recurre a la renderización del lado del cliente.
+- **None:** Sin alternativa. Angular no gestionará las peticiones de rutas que no estén pre-renderizadas.
```ts
// app.routes.server.ts
@@ -231,22 +231,22 @@ export const serverRoutes: ServerRoute[] = [
{
path: 'post/:id',
renderMode: RenderMode.Prerender,
- fallback: PrerenderFallback.Client, // Fallback to CSR if not prerendered
+ fallback: PrerenderFallback.Client, // Recurre a CSR si no está pre-renderizado
async getPrerenderParams() {
- // This function returns an array of objects representing prerendered posts at the paths:
- // `/post/1`, `/post/2`, and `/post/3`.
- // The path `/post/4` will utilize the fallback behavior if it's requested.
+ // Esta función retorna un array de objetos que representan posts pre-renderizados en las rutas:
+ // `/post/1`, `/post/2`, y `/post/3`.
+ // La ruta `/post/4` utilizará el comportamiento de alternativa si es solicitada.
return [{ id: 1 }, { id: 2 }, { id: 3 }];
},
},
];
```
-## Authoring server-compatible components
+## Creando componentes compatibles con el servidor
-Some common browser APIs and capabilities might not be available on the server. Applications cannot make use of browser-specific global objects like `window`, `document`, `navigator`, or `location` as well as certain properties of `HTMLElement`.
+Algunas APIs y capacidades comunes del navegador pueden no estar disponibles en el servidor. Las aplicaciones no pueden hacer uso de objetos globales específicos del navegador como `window`, `document`, `navigator` o `location`, así como ciertas propiedades de `HTMLElement`.
-In general, code which relies on browser-specific symbols should only be executed in the browser, not on the server. This can be enforced through the `afterEveryRender` and `afterNextRender` lifecycle hooks. These are only executed on the browser and skipped on the server.
+En general, el código que depende de símbolos específicos del navegador solo debe ejecutarse en el navegador, no en el servidor. Esto puede aplicarse mediante los hooks de ciclo de vida `afterEveryRender` y `afterNextRender`. Estos solo se ejecutan en el navegador y se omiten en el servidor.
```angular-ts
import { Component, viewChild, afterNextRender } from '@angular/core';
@@ -260,23 +260,23 @@ export class MyComponent {
constructor() {
afterNextRender(() => {
- // Safe to check `scrollHeight` because this will only run in the browser, not the server.
+ // Es seguro verificar `scrollHeight` porque esto solo se ejecutará en el navegador, no en el servidor.
console.log('content height: ' + this.contentRef().nativeElement.scrollHeight);
});
}
}
```
-## Setting providers on the server
+## Configurando proveedores en el servidor
-On the server side, top level provider values are set once when the application code is initially parsed and evaluated.
-This means that providers configured with `useValue` will keep their value across multiple requests, until the server application is restarted.
+En el lado del servidor, los valores de los proveedores de nivel superior se establecen una vez cuando el código de la aplicación se parsea y evalúa inicialmente.
+Esto significa que los proveedores configurados con `useValue` mantendrán su valor entre múltiples peticiones, hasta que la aplicación del servidor se reinicie.
-If you want to generate a new value for each request, use a factory provider with `useFactory`. The factory function will run for every incoming request, ensuring that a new value is created and assigned to the token each time.
+Si deseas generar un nuevo valor para cada petición, usa un proveedor factory con `useFactory`. La función factory se ejecutará para cada petición entrante, asegurando que se cree un nuevo valor y se asigne al token cada vez.
-## Accessing Document via DI
+## Accediendo a Document mediante DI
-When working with server-side rendering, you should avoid directly referencing browser-specific globals like `document`. Instead, use the [`DOCUMENT`](api/core/DOCUMENT) token to access the document object in a platform-agnostic way.
+Cuando se trabaja con renderización del lado del servidor, debes evitar referenciar directamente objetos globales específicos del navegador como `document`. En su lugar, usa el token [`DOCUMENT`](api/core/DOCUMENT) para acceder al objeto document de una manera agnóstica a la plataforma.
```ts
import { Injectable, inject, DOCUMENT } from '@angular/core';
@@ -285,8 +285,8 @@ import { Injectable, inject, DOCUMENT } from '@angular/core';
export class CanonicalLinkService {
private readonly document = inject(DOCUMENT);
- // During server rendering, inject a tag
- // so the generated HTML includes the correct canonical URL
+ // Durante la renderización en el servidor, inyecta una etiqueta
+ // para que el HTML generado incluya la URL canónica correcta
setCanonical(href: string): void {
const link = this.document.createElement('link');
link.rel = 'canonical';
@@ -297,15 +297,15 @@ export class CanonicalLinkService {
```
-HELPFUL: For managing meta tags, Angular provides the `Meta` service.
+ÚTIL: Para gestionar metaetiquetas, Angular proporciona el servicio `Meta`.
-## Accessing Request and Response via DI
+## Accediendo a Request y Response mediante DI
-The `@angular/core` package provides several tokens for interacting with the server-side rendering environment. These tokens give you access to crucial information and objects within your Angular application during SSR.
+El paquete `@angular/core` proporciona varios tokens para interactuar con el entorno de renderización del lado del servidor. Estos tokens te dan acceso a información crucial y objetos dentro de tu aplicación Angular durante SSR.
-- **[`REQUEST`](api/core/REQUEST 'API reference'):** Provides access to the current request object, which is of type [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) from the Web API. This allows you to access headers, cookies, and other request information.
-- **[`RESPONSE_INIT`](api/core/RESPONSE_INIT 'API reference'):** Provides access to the response initialization options, which is of type [`ResponseInit`](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#parameters) from the Web API. This allows you to set headers and the status code for the response dynamically. Use this token to set headers or status codes that need to be determined at runtime.
-- **[`REQUEST_CONTEXT`](api/core/REQUEST_CONTEXT 'API reference'):** Provides access to additional context related to the current request. This context can be passed as the second parameter of the [`handle`](api/ssr/AngularAppEngine#handle 'API reference') function. Typically, this is used to provide additional request-related information that is not part of the standard Web API.
+- **[`REQUEST`](api/core/REQUEST 'API reference'):** Proporciona acceso al objeto de petición actual, que es de tipo [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) de la Web API. Esto te permite acceder a encabezados, cookies y otra información de la petición.
+- **[`RESPONSE_INIT`](api/core/RESPONSE_INIT 'API reference'):** Proporciona acceso a las opciones de inicialización de la respuesta, que es de tipo [`ResponseInit`](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#parameters) de la Web API. Esto te permite establecer encabezados y el código de estado para la respuesta de forma dinámica. Usa este token para establecer encabezados o códigos de estado que necesiten determinarse en tiempo de ejecución.
+- **[`REQUEST_CONTEXT`](api/core/REQUEST_CONTEXT 'API reference'):** Proporciona acceso a contexto adicional relacionado con la petición actual. Este contexto puede pasarse como el segundo parámetro de la función [`handle`](api/ssr/AngularAppEngine#handle 'API reference'). Típicamente, se usa para proporcionar información adicional relacionada con la petición que no forma parte de la Web API estándar.
```angular-ts
import { inject, REQUEST } from '@angular/core';
@@ -322,20 +322,20 @@ export class MyComponent {
}
```
-IMPORTANT: The above tokens will be `null` in the following scenarios:
+IMPORTANTE: Los tokens anteriores serán `null` en los siguientes escenarios:
-- During the build processes.
-- When the application is rendered in the browser (CSR).
-- When performing static site generation (SSG).
-- During route extraction in development (at the time of the request).
+- Durante los procesos de compilación.
+- Cuando la aplicación se renderiza en el navegador (CSR).
+- Cuando se realiza generación de sitios estáticos (SSG).
+- Durante la extracción de rutas en desarrollo (en el momento de la petición).
-## Generate a fully static application
+## Generar una aplicación completamente estática
-By default, Angular prerenders your entire application and generates a server file for handling requests. This allows your app to serve pre-rendered content to users. However, if you prefer a fully static site without a server, you can opt out of this behavior by setting the `outputMode` to `static` in your `angular.json` configuration file.
+De forma predeterminada, Angular pre-renderiza toda tu aplicación y genera un archivo de servidor para gestionar las peticiones. Esto permite que tu aplicación sirva contenido pre-renderizado a los usuarios. Sin embargo, si prefieres un sitio completamente estático sin servidor, puedes optar por no usar este comportamiento estableciendo `outputMode` en `static` en tu archivo de configuración `angular.json`.
-When `outputMode` is set to `static`, Angular generates pre-rendered HTML files for each route at build time, but it does not generate a server file or require a Node.js server to serve the app. This is useful for deploying to static hosting providers where a backend server is not needed.
+Cuando `outputMode` está establecido en `static`, Angular genera archivos HTML pre-renderizados para cada ruta en tiempo de compilación, pero no genera un archivo de servidor ni requiere un servidor Node.js para servir la aplicación. Esto es útil para desplegar en proveedores de alojamiento estático donde no se necesita un servidor backend.
-To configure this, update your `angular.json` file as follows:
+Para configurar esto, actualiza tu archivo `angular.json` de la siguiente manera:
```json
{
@@ -353,16 +353,16 @@ To configure this, update your `angular.json` file as follows:
}
```
-## Caching data when using HttpClient
+## Almacenando datos en caché al usar HttpClient
-`HttpClient` caches outgoing network requests when running on the server. This information is serialized and transferred to the browser as part of the initial HTML sent from the server. In the browser, `HttpClient` checks whether it has data in the cache and if so, reuses it instead of making a new HTTP request during initial application rendering. `HttpClient` stops using the cache once an application becomes [stable](api/core/ApplicationRef#isStable) while running in a browser.
+`HttpClient` almacena en caché las peticiones de red salientes cuando se ejecuta en el servidor. Esta información se serializa y transfiere al navegador como parte del HTML inicial enviado desde el servidor. En el navegador, `HttpClient` verifica si tiene datos en la caché y, de ser así, los reutiliza en lugar de realizar una nueva petición HTTP durante la renderización inicial de la aplicación. `HttpClient` deja de usar la caché una vez que la aplicación se vuelve [estable](api/core/ApplicationRef#isStable) mientras se ejecuta en un navegador.
-### Configuring the caching options
+### Configurando las opciones de caché
-You can customize how Angular caches HTTP responses during server‑side rendering (SSR) and reuses them during hydration by configuring `HttpTransferCacheOptions`.
-This configuration is provided globally using `withHttpTransferCacheOptions` inside `provideClientHydration()`.
+Puedes personalizar cómo Angular almacena en caché las respuestas HTTP durante la renderización del lado del servidor (SSR) y las reutiliza durante la hidratación configurando `HttpTransferCacheOptions`.
+Esta configuración se proporciona globalmente usando `withHttpTransferCacheOptions` dentro de `provideClientHydration()`.
-By default, `HttpClient` caches all `HEAD` and `GET` requests which don't contain `Authorization` or `Proxy-Authorization` headers. You can override those settings by using `withHttpTransferCacheOptions` to the hydration configuration.
+De forma predeterminada, `HttpClient` almacena en caché todas las peticiones `HEAD` y `GET` que no contienen encabezados `Authorization` o `Proxy-Authorization`. Puedes sobrescribir esas configuraciones usando `withHttpTransferCacheOptions` en la configuración de hidratación.
```ts
import { bootstrapApplication } from '@angular/platform-browser';
@@ -386,8 +386,8 @@ bootstrapApplication(AppComponent, {
### `includeHeaders`
-Specifies which headers from the server response should be included in cached entries.
-No headers are included by default.
+Especifica qué encabezados de la respuesta del servidor deben incluirse en las entradas almacenadas en caché.
+De forma predeterminada no se incluye ningún encabezado.
```ts
withHttpTransferCacheOptions({
@@ -395,14 +395,14 @@ withHttpTransferCacheOptions({
});
```
-IMPORTANT: Avoid including sensitive headers like authentication tokens. These can leak user‑specific data between requests.
+IMPORTANTE: Evita incluir encabezados sensibles como tokens de autenticación. Estos pueden filtrar datos específicos del usuario entre peticiones.
---
### `includePostRequests`
-By default, only `GET` and `HEAD` requests are cached.
-You can enable caching for `POST` requests when they are used as read operations such as GraphQL queries.
+De forma predeterminada, solo se almacenan en caché las peticiones `GET` y `HEAD`.
+Puedes habilitar el almacenamiento en caché para peticiones `POST` cuando se usan como operaciones de lectura, como consultas GraphQL.
```ts
withHttpTransferCacheOptions({
@@ -410,14 +410,14 @@ withHttpTransferCacheOptions({
});
```
-Use this only when `POST` requests are **idempotent** and safe to reuse between server and client renders.
+Usa esto solo cuando las peticiones `POST` sean **idempotentes** y seguras para reutilizar entre renderizaciones del servidor y del cliente.
---
### `includeRequestsWithAuthHeaders`
-Determines whether requests containing `Authorization` or `Proxy‑Authorization` headers are eligible for caching.
-By default, these are excluded to prevent caching user‑specific responses.
+Determina si las peticiones que contienen encabezados `Authorization` o `Proxy‑Authorization` son elegibles para el almacenamiento en caché.
+De forma predeterminada, estas se excluyen para evitar el almacenamiento en caché de respuestas específicas del usuario.
```ts
withHttpTransferCacheOptions({
@@ -425,24 +425,24 @@ withHttpTransferCacheOptions({
});
```
-Enable only when authentication headers do **not** affect the response content (for example, public tokens for analytics APIs).
+Habilita esto solo cuando los encabezados de autenticación **no** afecten el contenido de la respuesta (por ejemplo, tokens públicos para APIs de analíticas).
-### Per‑request overrides
+### Anulaciones por petición
-You can override caching behavior for a specific request using the `transferCache` request option.
+Puedes anular el comportamiento de caché para una petición específica usando la opción de petición `transferCache`.
```ts
-// Include specific headers for this request
+// Incluir encabezados específicos para esta petición
http.get('/api/profile', { transferCache: { includeHeaders: ['CustomHeader'] } });
```
-### Disabling caching
+### Deshabilitando la caché
-You can disable HTTP caching of requests sent from the server either globally or individually.
+Puedes deshabilitar el almacenamiento en caché HTTP de las peticiones enviadas desde el servidor de forma global o individual.
-#### Globally
+#### Globalmente
-To disable caching for all requests in your application, use the `withNoHttpTransferCache` feature:
+Para deshabilitar la caché para todas las peticiones en tu aplicación, usa la característica `withNoHttpTransferCache`:
```ts
import { bootstrapApplication, provideClientHydration, withNoHttpTransferCache } from '@angular/platform-browser';
@@ -456,7 +456,7 @@ bootstrapApplication(AppComponent, {
#### `filter`
-You can also selectively disable caching for certain requests using the [`filter`](api/common/http/HttpTransferCacheOptions) option in `withHttpTransferCacheOptions`. For example, you can disable caching for a specific API endpoint:
+También puedes deshabilitar selectivamente la caché para ciertas peticiones usando la opción [`filter`](api/common/http/HttpTransferCacheOptions) en `withHttpTransferCacheOptions`. Por ejemplo, puedes deshabilitar la caché para un endpoint específico de la API:
```ts
import { bootstrapApplication, provideClientHydration, withHttpTransferCacheOptions } from '@angular/platform-browser';
@@ -470,21 +470,21 @@ bootstrapApplication(AppComponent, {
});
```
-Use this option to exclude endpoints with user‑specific or dynamic data (for example `/api/profile`).
+Usa esta opción para excluir endpoints con datos específicos del usuario o dinámicos (por ejemplo, `/api/profile`).
-#### Individually
+#### Individualmente
-To disable caching for an individual request, you can specify the [`transferCache`](api/common/http/HttpRequest#transferCache) option in an `HttpRequest`.
+Para deshabilitar la caché para una petición individual, puedes especificar la opción [`transferCache`](api/common/http/HttpRequest#transferCache) en un `HttpRequest`.
```ts
httpClient.get('/api/sensitive-data', { transferCache: false });
```
-## Configuring a server
+## Configurando un servidor
### Node.js
-The `@angular/ssr/node` extends `@angular/ssr` specifically for Node.js environments. It provides APIs that make it easier to implement server-side rendering within your Node.js application. For a complete list of functions and usage examples, refer to the [`@angular/ssr/node` API reference](api/ssr/node/AngularNodeAppEngine) API reference.
+`@angular/ssr/node` extiende `@angular/ssr` específicamente para entornos Node.js. Proporciona APIs que facilitan la implementación de la renderización del lado del servidor dentro de tu aplicación Node.js. Para una lista completa de funciones y ejemplos de uso, consulta la referencia de API de [`@angular/ssr/node`](api/ssr/node/AngularNodeAppEngine).
```ts
// server.ts
@@ -501,21 +501,21 @@ app.use('*', (req, res, next) => {
if (response) {
writeResponseToNodeResponse(response, res);
} else {
- next(); // Pass control to the next middleware
+ next(); // Pasar el control al siguiente middleware
}
})
.catch(next);
});
/**
- * The request handler used by the Angular CLI (dev-server and during build).
+ * El manejador de peticiones usado por Angular CLI (servidor de desarrollo y durante la compilación).
*/
export const reqHandler = createNodeRequestHandler(app);
```
### Non-Node.js
-The `@angular/ssr` provides essential APIs for server-side rendering your Angular application on platforms other than Node.js. It leverages the standard [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) and [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) objects from the Web API, enabling you to integrate Angular SSR into various server environments. For detailed information and examples, refer to the [`@angular/ssr` API reference](api/ssr/AngularAppEngine).
+`@angular/ssr` proporciona APIs esenciales para renderizar tu aplicación Angular del lado del servidor en plataformas distintas a Node.js. Aprovecha los objetos estándar [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) y [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) de la Web API, lo que te permite integrar Angular SSR en diversos entornos de servidor. Para información detallada y ejemplos, consulta la referencia de API de [`@angular/ssr`](api/ssr/AngularAppEngine).
```ts
// server.ts
@@ -524,7 +524,7 @@ import { AngularAppEngine, createRequestHandler } from '@angular/ssr';
const angularApp = new AngularAppEngine();
/**
- * This is a request handler used by the Angular CLI (dev-server and during build).
+ * Este es un manejador de peticiones usado por Angular CLI (servidor de desarrollo y durante la compilación).
*/
export const reqHandler = createRequestHandler(async (req: Request) => {
const res: Response|null = await angularApp.render(req);