Written by: developervsandhu
Technology and Gadgets
Setup Dyanmic Subdomain
Setup subdomain like vercel dynamically
- First we need to setup express js and typescript server
pnpm install express
pnpm install -D @types/express@4 ts-node @types/node typescript
pnpm tsc init
- Initialize your tsconfig.json
pnpm tsc --init
- Add following options to tsconfig
"typeRoots": ["./src/types", "./node_modules/@types"],
"rootDir": "./src",
"outDir": "./dist"
- Add the following code to your index.ts
- First we need to setup types
// Add subdomain type to express request
declare global {
namespace Express {
interface Request {
subdomainUser?: string;
}
}
}
- Add middleware to detect subdomain
// Subdomain detection middleware
app.use((req: Request, res: Response, next: NextFunction) => {
const host = req.headers.host;
const subdomain = host?.split(".")[0];
if (
subdomain &&
subdomain !== "www" &&
subdomain !== "localhost:3000" &&
!/^\d+\.\d+\.\d+\.\d+$/.test(subdomain) // ignore IP addresses
) {
req.subdomainUser = subdomain;
}
next();
});
- Then in the main route we can handle subdomain thing
app.get("/", async (req: Request, res: Response) => {
const subdomain = req.subdomainUser;
if (subdomain && validSubdomains.includes(subdomain as any)) {
const themeData =
AbstractThemeOptionsSubDomain[
subdomain as keyof typeof AbstractThemeOptionsSubDomain
];
const html = await engine.renderFile("abstract/index", {
...themeData,
subdomain,
});
return res.send(html);
}
const html = await engine.renderFile("abstract/index", AbstractThemeOptions);
res.send(html);
});
- Good To Go Your Subdomain server is done
Login To Add Comment
No comments yet.