-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add compression and cookie docs (#8)
- Loading branch information
Showing
7 changed files
with
383 additions
and
34 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
--- | ||
sidebar_position: 1 | ||
--- | ||
|
||
# Compression | ||
|
||
The npm compression package is a middleware that can compress response bodies for requests that traverse through it, which can help reduce the size of data that's sent over the network, leading to quicker response times and lower bandwidth usage. It uses the zlib library to perform gzip or deflate compression, both of which are widely supported by modern web browsers. | ||
|
||
## Compression package | ||
|
||
- Performance: It can significantly reduce the size of the response body, thereby decreasing the time it takes for a client to download the response and render the content. | ||
|
||
- Efficiency: It helps in reducing bandwidth consumption which is especially useful if your server is sending large amounts of data or if you have limited bandwidth. | ||
|
||
- Overhead: While compression reduces the size of the response body, it does add some computational overhead on the server-side as the server must compress the response body before sending it. | ||
|
||
:::caution COMPRESSION OVERHEAD | ||
This might not be ideal for high traffic websites where server resources are at a premium. | ||
::: | ||
|
||
Not all content benefits from compression. Binary files like images and videos are already compressed and trying to compress them further can sometimes even increase their size. | ||
|
||
## When to use | ||
|
||
Deciding on when to use compression depends on the use case. If your website serves a lot of textual data (HTML, CSS, JS, JSON, XML etc.), then using the npm compression package can result in significant bandwidth savings and performance benefits. However, if your website is extremely high traffic, the additional computational overhead of compression might start to become a bottleneck. | ||
|
||
In high traffic scenarios, it might be more beneficial to use a reverse proxy or a CDN (Content Delivery Network) which can serve static assets and perform caching. This can offload some of the traffic from your main servers and also serve content from locations geographically closer to users, resulting in faster response times. These services usually handle compression themselves, meaning you wouldn't need to use the npm compression package. | ||
|
||
Modern approaches could involve a combination of techniques - serving static assets from a CDN, caching responses where appropriate, utilizing HTTP/2 for multiplexing, and splitting up your application into microservices to distribute the load. | ||
|
||
Remember, these approaches aren't mutually exclusive. Often the best approach is to use a combination of these techniques based on the specific requirements of your application. Testing and monitoring your application under realistic workloads can help you make the best decision. | ||
|
||
## Use with ExpressoTS | ||
|
||
Install the npm compression middleware. | ||
|
||
```bash | ||
npm i compression | ||
``` | ||
|
||
After Installation you can add the middleware to your ExpressoTS app. | ||
|
||
```typescript | ||
import compression from "compression"; | ||
|
||
// Add in the application create method in the middleware array | ||
AppInstance.create(container, [compression()]); | ||
``` | ||
|
||
Here is another example: using compress with filters, filtering requests that contain payload bodies larger than 100 * 1024 bytes: | ||
|
||
```typescript | ||
AppInstance.create(container, [ | ||
compression({ | ||
level: 6, | ||
threshold: 100 * 1024, | ||
filter: (req, res) => { | ||
if (req.headers["x-no-compression"]) { | ||
return false; | ||
} | ||
return compression.filter(req, res); | ||
}, | ||
}), | ||
]); | ||
``` | ||
|
||
:::tip | ||
For more information about the npm compression package, please visit the **[npm compression package](https://www.npmjs.com/package/compression)**. | ||
::: | ||
|
||
--- | ||
|
||
## Support the project | ||
|
||
ExpressoTS is an MIT-licensed open source project. It's an independent project with ongoing development made possible thanks to your support. If you'd like to help, please consider: | ||
|
||
- Become a sponsor on **[Sponsor no GitHub](https://github.com/sponsors/expressots)** | ||
- Follow the **[organization](https://github.com/expressots)** on GitHub and Star ⭐ the project | ||
- Subscribe to the Twitch channel: **[Richard Zampieri](https://www.twitch.tv/richardzampieri)** | ||
- Join our **[Discord](https://discord.com/invite/PyPJfGK)** | ||
- Contribute submitting **[issues and pull requests](https://github.com/expressots/expressots/issues/new/choose)** | ||
- Share the project with your friends and colleagues |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
--- | ||
sidebar_position: 2 | ||
--- | ||
|
||
# Cookies | ||
|
||
Cookies are small pieces of data that a website sends to a user's web browser while the user is browsing that website. Every time the user loads the website, the browser sends the cookie back to the server to notify the website of the user's previous activity. | ||
|
||
Cookies serve several primary purposes: | ||
|
||
1. Session Management: | ||
Cookies are often used to handle user sessions. For example, when you log into a website, a cookie is set to remember your login state. So, as you navigate the site, you remain logged in. | ||
|
||
2. Personalization: | ||
Cookies can store user preferences to personalize the user's experience on the site. For example, cookies might store information about the user's preferred language, theme, or other settings. | ||
|
||
3. Tracking: | ||
Some cookies track user behavior on the site over time. These are often used by third-party analytics tools to understand user behavior and optimize the site accordingly. Advertisers also use tracking cookies to display targeted ads based on user activity. | ||
|
||
4. Security: | ||
Cookies can be used to support secure website functions. For example, a cookie can be used to remember that a user has authenticated to a site so that the server knows the user has already provided valid login credentials. | ||
|
||
It's also important to note that there are different types of cookies - session cookies, which expire when the browser session ends, and persistent cookies, which remain on the user's device for a set period of time or until they are explicitly deleted. | ||
|
||
:::caution USING COOKIE FOR TRACKING | ||
Have in mind that the use of cookies, especially for tracking and personalization, has raised privacy concerns, leading to regulations such as GDPR in Europe and CCPA in California that require sites to disclose their cookie usage and obtain user consent. | ||
::: | ||
|
||
## Cookie-parser package | ||
|
||
- Ease of Use: cookie-parser makes it very easy to read cookie values, which are often used for tracking user sessions, personalization, and managing stateful applications. Without this library, you would have to manually parse the Cookie header and handle the nuances of cookie formatting. | ||
|
||
- Signed Cookies: The package also supports signed cookies, which are a way to verify the integrity of cookies (i.e., whether they have been tampered with). This is an important feature for securing sensitive information stored in cookies. | ||
|
||
## What to consider when using cookie-parser | ||
|
||
- Overhead: While it's not a heavy library, using cookie-parser does add a bit of overhead to each request, as it parses all cookies regardless of whether they are used in the route handler. | ||
|
||
- Stateful: Cookies inherently make an application stateful. When scaling an application, state can be problematic. Therefore, alternative stateless authentication methods, like tokens, can be preferable in a microservices architecture. | ||
|
||
## When to use | ||
|
||
Deciding when to use cookie-parser largely depends on your application's needs. If your web application requires state management and you've chosen to do that via cookies, cookie-parser can make your life easier and your application more secure with signed cookies. | ||
|
||
However, if your website has heavy traffic, the overhead might become a concern. If your architecture is based around stateless services (common in microservices architectures), you might want to avoid cookies and opt for other methods of maintaining state, like JWTs (JSON Web Tokens). | ||
|
||
:::info | ||
In case you're dealing with a high traffic website, consider alternatives like sessions stored in a database, JWTs, or tokens stored in HTTP headers. Also, using a load balancer to distribute traffic and session store modules to maintain session data across multiple servers can help to manage high traffic and stateful data. | ||
::: | ||
|
||
Just like before, the best approach often involves combining multiple techniques, tailored to your application's specific needs. Testing and monitoring your application under realistic conditions can help guide your decision-making process. | ||
|
||
## Use with ExpressoTS | ||
|
||
Install the npm cookie-parser middleware and type definition. | ||
|
||
```bash | ||
npm i cookie-parser | ||
npm i -D @types/cookie-parser | ||
``` | ||
|
||
After the installation you can add the middleware to your ExpressoTS app. | ||
|
||
```typescript | ||
import cookieParser from "cookie-parser"; | ||
|
||
// Add in the application create method in the middleware array | ||
AppInstance.create(container, [cookieParser()]); | ||
``` | ||
|
||
Here is an example of how to use cookie-parser: | ||
|
||
Set a cookie with a random UUID as value, that expires in 1 hour and is only accessible via HTTP: | ||
|
||
```typescript | ||
@httpGet("set-cookie") | ||
setCookie(@response() res: Response) { | ||
res.cookie("authToken", randomUUID(), { | ||
maxAge: 60 * 60 * 1000, // 1 hour | ||
httpOnly: true, | ||
}); | ||
return res.send("Cookie set!"); | ||
} | ||
``` | ||
|
||
Get a cookie: | ||
|
||
```typescript | ||
@httpGet("get-cookie") | ||
getCookie(@cookies() cookieInfo: string, @response() res: Response) { | ||
return res.send(`Your token: ${cookieInfo["authToken"]}`); | ||
} | ||
``` | ||
|
||
:::tip | ||
Note that we are using `@cookies()` decorator to get the cookie information. This decorator is provided by inversify-express-utils. | ||
::: | ||
|
||
--- | ||
|
||
## Support the project | ||
|
||
ExpressoTS is an MIT-licensed open source project. It's an independent project with ongoing development made possible thanks to your support. If you'd like to help, please consider: | ||
|
||
- Become a sponsor on **[Sponsor no GitHub](https://github.com/sponsors/expressots)** | ||
- Follow the **[organization](https://github.com/expressots)** on GitHub and Star ⭐ the project | ||
- Subscribe to the Twitch channel: **[Richard Zampieri](https://www.twitch.tv/richardzampieri)** | ||
- Join our **[Discord](https://discord.com/invite/PyPJfGK)** | ||
- Contribute submitting **[issues and pull requests](https://github.com/expressots/expressots/issues/new/choose)** | ||
- Share the project with your friends and colleagues |
This file was deleted.
Oops, something went wrong.
4 changes: 2 additions & 2 deletions
4
i18n/pt/docusaurus-plugin-content-docs/current/tutorials/_category_.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,8 @@ | ||
{ | ||
"label": "Tutorials", | ||
"label": "Tutoriais", | ||
"position": 5, | ||
"link": { | ||
"type": "generated-index", | ||
"description": "Expresso TS Tutorials." | ||
"description": "Expresso TS Tutoriais." | ||
} | ||
} |
83 changes: 83 additions & 0 deletions
83
i18n/pt/docusaurus-plugin-content-docs/current/tutorials/compression.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
--- | ||
sidebar_position: 1 | ||
--- | ||
|
||
# Compressão | ||
|
||
O pacote npm compression é um middleware que pode comprimir corpos de resposta para solicitações que passam por ele, o que pode ajudar a reduzir o tamanho dos dados que são enviados pela rede, levando a tempos de resposta mais rápidos e uso menor de largura de banda. Ele usa a biblioteca zlib para realizar a compressão gzip ou deflate, ambos amplamente suportados pelos navegadores da web modernos. | ||
|
||
## Pacote de compressão | ||
|
||
- Desempenho: Pode reduzir significativamente o tamanho do corpo da resposta, diminuindo assim o tempo que um cliente leva para baixar a resposta e renderizar o conteúdo. | ||
|
||
- Eficiência: Ajuda na redução do consumo de largura de banda, o que é especialmente útil se o seu servidor estiver enviando grandes quantidades de dados ou se você tiver largura de banda limitada. | ||
Contras do pacote npm Compression: | ||
|
||
- Sobrecarga: Embora a compressão reduza o tamanho do corpo da resposta, ela adiciona alguma sobrecarga computacional do lado do servidor, pois o servidor deve comprimir o corpo da resposta antes de enviá-lo. | ||
|
||
:::caution SOBRECARGA DA COMPRESSÃO | ||
Isso pode não ser ideal para sites de alto tráfego onde os recursos do servidor estão em alta demanda. | ||
::: | ||
|
||
Nem todo conteúdo se beneficia da compressão. Arquivos binários como imagens e vídeos já são comprimidos e tentar comprimi-los ainda mais às vezes pode até aumentar o tamanho deles. | ||
|
||
## Quando usar | ||
|
||
Decidir quando usar a compressão depende do caso de uso. Se o seu site serve muitos dados textuais (HTML, CSS, JS, JSON, XML etc.), então usar o pacote de compressão npm pode resultar em economias significativas de largura de banda e benefícios de desempenho. No entanto, se o seu site tem um tráfego extremamente alto, a sobrecarga computacional adicional da compressão pode começar a se tornar um gargalo. | ||
|
||
Em cenários de alto tráfego, pode ser mais benéfico usar um proxy reverso ou uma CDN (Rede de Entrega de Conteúdo) que pode servir ativos estáticos e realizar caching. Isso pode desviar parte do tráfego dos seus servidores principais e também servir conteúdo de locais geograficamente mais próximos dos usuários, resultando em tempos de resposta mais rápidos. Esses serviços geralmente lidam com a compressão por conta própria, o que significa que você não precisaria usar o pacote de compressão npm. | ||
|
||
As abordagens modernas podem envolver uma combinação de técnicas - servir ativos estáticos de uma CDN, armazenar em cache respostas quando apropriado, utilizar HTTP/2 para multiplexação e dividir seu aplicativo em microserviços para distribuir a carga. | ||
|
||
Lembre-se, essas abordagens não são mutuamente exclusivas. Muitas vezes, a melhor abordagem é usar uma combinação dessas técnicas com base nos requisitos específicos do seu aplicativo. Testar e monitorar seu aplicativo sob cargas de trabalho realistas pode ajudá-lo a tomar a melhor decisão. | ||
|
||
## Usar com ExpressoTS | ||
|
||
Instale o middleware de compressão npm. | ||
|
||
```bash | ||
npm i compression | ||
``` | ||
|
||
Após a instalação, você pode adicionar o middleware ao seu aplicativo ExpressoTS. | ||
|
||
```typescript | ||
import compression from "compression"; | ||
|
||
// Adicione no método de criação do aplicativo no array de middleware | ||
AppInstance.create(container, [compression()]); | ||
``` | ||
|
||
Aqui está outro exemplo: usando compressão com filtros, filtrando solicitações que contêm corpos de carga útil maiores que 100 * 1024 bytes: | ||
|
||
```typescript | ||
AppInstance.create(container, [ | ||
compression({ | ||
level: 6, | ||
threshold: 100 * 1024, | ||
filter: (req, res) => { | ||
if (req.headers["x-no-compression"]) { | ||
return false; | ||
} | ||
return compression.filter(req, res); | ||
}, | ||
}), | ||
]); | ||
``` | ||
|
||
:::tip | ||
Para mais informações sobre o pacote de compressão npm, por favor visite o **[pacote compression do npm](https://www.npmjs.com/package/compression)**. | ||
::: | ||
|
||
--- | ||
|
||
## Apoie o projeto | ||
|
||
ExpressoTS é um projeto de código aberto licenciado sob o MIT. É um projeto independente com desenvolvimento contínuo possibilitado graças ao seu suporte. Se você deseja ajudar, por favor considere: | ||
|
||
- Se tornar um **[Sponsor no GitHub](https://github.com/sponsors/expressots)** | ||
- Siga a **[organização](https://github.com/expressots)** no GitHub e de um Star ⭐ no projeto | ||
- Subscreva no nosso canal na Twitch: **[Richard Zampieri](https://www.twitch.tv/richardzampieri)** | ||
- Entre no nosso **[Discord](https://discord.com/invite/PyPJfGK)** | ||
- Contribua submetendo **[issues e pull requests](https://github.com/expressots/expressots/issues/new/choose)** | ||
- Compartilhe o projeto com seus amigos e colegas |
Oops, something went wrong.