|
| 1 | +/** |
| 2 | + * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + */ |
| 7 | + |
| 8 | +import type {NextApiRequest, NextApiResponse} from 'next'; |
| 9 | +import {finishedTranslations} from 'utils/finishedTranslations'; |
| 10 | + |
| 11 | +export default async function handler( |
| 12 | + req: NextApiRequest, |
| 13 | + res: NextApiResponse |
| 14 | +) { |
| 15 | + if (req.method !== 'GET') { |
| 16 | + return res.status(405).end(); |
| 17 | + } |
| 18 | + |
| 19 | + const {language, from} = req.query; |
| 20 | + if ( |
| 21 | + typeof language !== 'string' || |
| 22 | + language === 'en' || |
| 23 | + !finishedTranslations.includes(language) |
| 24 | + ) { |
| 25 | + return res.status(404).end(); |
| 26 | + } |
| 27 | + |
| 28 | + const homepage = `https://${language}.react.dev/`; |
| 29 | + if ( |
| 30 | + typeof from !== 'string' || |
| 31 | + !/^\/(?!\/)(?:learn|reference)(?:\/|$)[^\\?#]*$/.test(from) |
| 32 | + ) { |
| 33 | + return res.redirect(302, homepage); |
| 34 | + } |
| 35 | + |
| 36 | + const translatedPage = new URL(from, homepage).toString(); |
| 37 | + const controller = new AbortController(); |
| 38 | + const timeout = setTimeout(() => controller.abort(), 2000); |
| 39 | + |
| 40 | + try { |
| 41 | + const response = await fetch(translatedPage, { |
| 42 | + method: 'HEAD', |
| 43 | + signal: controller.signal, |
| 44 | + }); |
| 45 | + if (response.ok) { |
| 46 | + return res.redirect(302, translatedPage); |
| 47 | + } |
| 48 | + } catch { |
| 49 | + // Keep the original homepage behavior when the translation site is unavailable. |
| 50 | + } finally { |
| 51 | + clearTimeout(timeout); |
| 52 | + } |
| 53 | + |
| 54 | + return res.redirect(302, homepage); |
| 55 | +} |
0 commit comments