The
app.subdomainOffset
setting in Koa.js is used to configure the offset at which Koa starts parsing subdomains. A subdomain is a part of a domain that is located before the main domain name. For example, in the subdomain api.example.com, "
api
" is the subdomain.
By default,
Koa.js
assumes that the domain has only one part (e.g., example.com) and any part before it is a subdomain. However, in some scenarios, especially when deploying applications on subdomains of top-level domains like
.co.uk
, the assumption may not hold true.
The
app.subdomainOffset
setting allows you to adjust the offset at which Koa starts considering parts of the domain as subdomains. This is particularly useful when dealing with domain names that have multiple parts.
Here's an example of how to use app.subdomainOffset :
const Koa = require('koa');
const app = new Koa();
// Set the subdomainOffset to 2
// This indicates that Koa should consider the third part of the domain as the subdomain
app.subdomainOffset = 2;
app.use(async (ctx) => {
// Access the subdomain using ctx.subdomains array
const subdomain = ctx.subdomains.join('.');
ctx.body = `Subdomain: ${subdomain}`;
});
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});?
In this example, if the server receives a request for
api.v1.example.com
, the
app.subdomainOffset
is set to 2, meaning Koa considers the third part of the domain (api) as the subdomain. The response would indicate that the subdomain is "
api
."
Adjusting the
app.subdomainOffset
is typically necessary when deploying applications in environments where the domain structure includes multiple parts, and the default assumption of Koa (that the first part is the subdomain) does not hold. By setting the offset correctly, you ensure that Koa accurately parses subdomains in your application.