Last active
July 26, 2022 19:03
-
-
Save kdby-io/17cc44abf359283e41d2a73d1ba79790 to your computer and use it in GitHub Desktop.
Example of custom domain feature with Express.js
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
const express = require('express') | |
const app = express() | |
const port = 80 | |
const users = [ | |
{ | |
username: 'alice', | |
name: 'Alice', | |
domain: 'alice.com', | |
}, | |
{ | |
username: 'bob', | |
name: 'Bob', | |
domain: 'bob.com', | |
}, | |
] | |
app.use((req, res, next) => { | |
if (req.hostname === 'example.com') { | |
return next(); | |
} | |
const user = users.find(user => user.domain === req.hostname); | |
if (!user) { | |
return res.sendStatus(404); | |
} | |
return res.send(`${user.username}, Hello World!`); | |
}); | |
app.get('/', (req, res) => res.send('Hello World!')) | |
app.get('/:username', (req, res) => { | |
const user = users.find(user => user.username === req.params.username) | |
if (!user) { | |
return res.sendStatus(404) | |
} | |
return res.send(`${user.name}, Hello World!`) | |
}); | |
app.listen(port, () => console.log('Server ON!')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment