Skip to content

Commit

Permalink
feat: override index.html lang w/ cookie pref
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobcolyvan committed Aug 14, 2024
1 parent b5d46bc commit 38c6b65
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 3 deletions.
1 change: 1 addition & 0 deletions api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"compression": "^1.7.4",
"connect-redis": "^7.1.0",
"cookie": "^0.5.0",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
Expand Down
18 changes: 17 additions & 1 deletion api/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ const express = require('express');
const compression = require('compression');
const passport = require('passport');
const mongoSanitize = require('express-mongo-sanitize');
const fs = require('fs');
const cookieParser = require('cookie-parser');
const { jwtLogin, passportLogin } = require('~/strategies');
const { connectDb, indexSync } = require('~/lib/db');
const { isEnabled } = require('~/server/utils');
Expand Down Expand Up @@ -50,6 +52,7 @@ const startServer = async () => {
app.use(staticCache(app.locals.paths.assets));
app.set('trust proxy', 1); // trust first proxy
app.use(cors());
app.use(cookieParser());

if (DISABLE_COMPRESSION !== 'true') {
app.use(compression());
Expand Down Expand Up @@ -101,8 +104,21 @@ const startServer = async () => {
app.use('/api/roles', routes.roles);

app.use('/api/tags', routes.tags);

app.use((req, res) => {
res.sendFile(path.join(app.locals.paths.dist, 'index.html'));
// Check for preferred language in cookies, else check accept-language header
const preferredLanguage =
req.cookies.langcode || req.headers['accept-language']?.split(',')[0] || 'en-US';
const indexPath = path.join(app.locals.paths.dist, 'index.html');

fs.readFile(indexPath, 'utf8', (err, data) => {
if (err) {
console.error('Error reading index file:', err);
return res.status(500).send('Internal Server Error');
}
const updatedIndexHtml = data.replace(/lang="en-US"/g, `lang="${preferredLanguage}"`);
res.send(updatedIndexHtml);
});
});

app.listen(port, host, () => {
Expand Down
2 changes: 1 addition & 1 deletion client/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
type="image/png"
sizes="16x16"
href="/assets/favicon-16x16.png"
/>
/>
<link
rel="apple-touch-icon"
href="/assets/apple-touch-icon-180x180.png"
Expand Down
39 changes: 38 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 38c6b65

Please sign in to comment.