Serve an i18n angular app on Firebase using functions

╄→гoц情女王★ 提交于 2020-01-14 04:08:10

问题


I'm trying to handle requests correctly to a localized angular app hosted on Firebase. The goal is to load the right app bundle depending on: 1) A cookie named locale. 2) The accept-language header. 3) Default to en-us when others are unavailable.

When localizing angular apps with i18n, angular-cli generates bundles (versions of your app) for each language/locale present in angular.json. Firebase serves your bundles as static content and it has serious security measurements disallowing path traversals.

I tried both setting rewrites and redirects in firebase.json but there is no facilities to intercept the locale cookie. Then, I used cloud functions to read the cookie, parse requests and return the right resource using express, cookie-parser and express-locale.

1. Using hosting only

firebase.json

{
  "hosting": {
    "public": "dist",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "/en-us/**",
        "destination": "/en-us/index.html"
      },
      {
        "source": "/es-co/**",
        "destination": "/es-co/index.html"
      },
      {
        "source": "/zh-hans/**",
        "destination": "/zh-hans/index.html"
      },
      {
        "source": "**",
        "destination": "/en-us/index.html"
      }
    ]
  }
}

2. Using cloud functions and express

firebase.json

{
  "functions": {
    "predeploy": [
      "npm --prefix \"$RESOURCE_DIR\" run lint"
    ]
  },
  "hosting": {
    "public": "dist",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "function": "multilang"
      }
    ]
  }
}

functions/index.js

const express = require('express')
const expressLocale = require('express-locale')
const cookieParser = require('cookie-parser')
const functions = require('firebase-functions')
const path = require('path')
const fs = require('fs')
const _ = require('lodash')

const app = express()

const localeMap = {
  en: 'en_US',
  es: 'es_CO',
  zh: 'zh_TW',
  'en-US': 'en_US',
  'es-CO': 'es_CO',
  'zh-TW': 'zh_TW',
  'zh-Hans': 'zh_TW',
  en_US: 'en_US',
  es_CO: 'es_CO',
  zh_TW: 'zh_TW',
  zh_Hans: 'zh_TW'
}

const defaultLocale = 'en_US'

const baseMap = {
  en_US: 'en-us',
  es_CO: 'es-co',
  zh_TW: 'zh-hans'
}

app
  .use(cookieParser())
  .use(expressLocale({
    priority: ['cookie', 'accept-language', 'map', 'default'],
    default: defaultLocale,
    map: localeMap
  }))
  .use('**', (req, res, next) => {
    const locale = localeMap[req.locale.language]
    const sanitized = req.originalUrl.replace(/\.{2,}/g, '').replace(/\/{2,}/g, '/')
    const url = sanitized.split('/')
    const idx = url.length === 1 ? 0 : 1

    url[0] = _.values(baseMap).includes(url[idx]) ?
      url[idx] : (baseMap[locale] || baseMap[defaultLocale])

    if (url.length > 1 && url[0] === url[1]) {
      url.shift()
    }

    let file = path.resolve(`dist/${url.join('/')}`)

    if (!url[url.length - 1].match(/^[\w,\s-]+\.[a-z0-9]{2,4}$/) || !fs.existsSync(file)) {
      file = path.resolve(`dist/${url[0]}/index.html`)
    }

    res.sendFile(file)
  })

exports.multilang = functions.https.onRequest(app)

The last settings work well for a local Firebase emulation resolving path to index.html or any other requested file (say it ngsw-worker.js for progressive apps support).

When deploying to Firebase it fails resolving and finding the hosted files (e.g. index.html), even if you change path to:

  • /${url[0]}/index.html
  • ../${url[0]}/index.html
  • /public/${url[0]}/index.html

Or rewriting req.sendFile to req.redirect.

Any help is appreciated.


回答1:


For anyone facing the same problem, here is a naive solution using firebase functions:

functions/index.js

const express = require('express')
const cookieParser = require('cookie-parser')
const expressLocale = require('express-locale')
const functions = require('firebase-functions')

const localeMap = {
  en: 'en_US',
  es: 'es_CO',
  zh: 'zh_CN',
  en_US: 'en_US',
  es_CO: 'es_CO',
  zh_Hans: 'zh_CN'
}

const prefixMap = {
  en_US: 'en-us',
  es_CO: 'es-co',
  zh_CN: 'zh-hans',
}

const defaultLocale = 'en_US'
const app = express()

app
  .use(cookieParser())
  .use(expressLocale({
    priority: ['cookie', 'accept-language', 'map', 'default'],
    default: defaultLocale,
    map: localeMap
  }))
  .use('*', (req, res, next) => {
    const locale = localeMap[req.locale.language]
    const prefix = prefixMap[locale] || prefixMap[defaultLocale]
    res.redirect(`/${prefix}${req.originalUrl}`)
  })

exports.multilang = functions.https.onRequest(app)

firebase.json

{
  "functions": {
    "predeploy": [
      "npm --prefix \"$RESOURCE_DIR\" run lint"
    ]
  },
  "hosting": {
    "public": "dist/your-app-name",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "/en-us/**",
        "destination": "/en-us/index.html"
      },
      {
        "source": "/es-co/**",
        "destination": "/es-co/index.html"
      },
      {
        "source": "/zh-hans/**",
        "destination": "/zh-hans/index.html"
      },
      {
        "source": "**",
        "function": "multilang"
      }
    ]
  }
}


来源:https://stackoverflow.com/questions/54340025/serve-an-i18n-angular-app-on-firebase-using-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!