This is for language translation on web page. I want to store and access translation files on CDN.
I want to access json or any static file and which is on CDN(content delivery network).
And that static file is private i.e. not accessible by public URL.
Need this solution for localization of an react app with quick response (hence storing static json file on CDN privately).
How can I access privately held file on CDN from react ?... is the main question
I tried i18next, i18next-http-backend.
It works with public file url.
I am not sure how to access private files from it.
Based on the docs, you can pass customHeaders options...
This means you could do something like this:
import i18next from 'i18next';
import HttpApi from 'i18next-http-backend';
i18next.use(HttpApi).init({
backend: {
loadPath: 'https://path-to-your-private-cdn',
customHeaders: {
authorization: 'some secret or whatever you need to be authorized'
}
},
});
Or alternatively use a service that offers this, like locize:
import i18next from 'i18next';
import LocizeBackend from 'i18next-locize-backend';
i18next.use(LocizeBackend).init({
backend: {
projectId: "[PROJECTID]",
apiKey: "[APIKEY]",
version: "[VERSION]",
private: true
}
});
Related
As I'm using Firebase Cloud Messaging in my React, it requires me to put the firebase-messaging-sw.js in my public folder.
In there, it is defining the function for the onBackgroundMessage, which I want to have an access to my module, and update some of my components in my src.
import { toast } from "react-toastify"; // or import my other modules
messaging.onBackgroundMessage(function(payload) {
console.log('Received background message ', payload);
//toast or do some updating my modules
toast(`Message received : ${payload}`) // here comes the error
});
But I got an error of
Uncaught SyntaxError: Cannot use import statement outside a module (at
firebase-messaging-sw.js:3:1)
How can I import my src module to the public folder?
How should I properly use the onBackgroundMessage in React?
is it normal to import module from src to the public folder?
Use importScripts to import scripts into the worker's scope like firebase-messaging itself.
importScripts('https://www.gstatic.com/firebasejs/9.2.0/firebase-messaging.js');
I am having great difficulty understanding why my bucket link is still going 403 despite the fact I have created the bucket, uploaded the bucket to S3 and now it is telling me that I am not able to access the link with the public link. The code looks good; why is this not working? Is this an IAM's issue that I am not configuring?
Below is my infrastructure-stack.ts file:
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as iam from 'aws-cdk-lib/aws-iam';
export class InfrastructureStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const bucket = new s3.Bucket(this, 'WebsiteBucket', {
// Specify Bucket Name Here
bucketName: 'example-cdk-project',
// Specify the index document for our website
websiteIndexDocument: 'index.html',
// Allow public access to our bucket
blockPublicAccess: new s3.BlockPublicAccess({ restrictPublicBuckets: false })
});
// Create a bucket policy allowing anyone to access the objects in bucket
const bucketPolicy = new iam.PolicyStatement({
actions: ['s3:GetObject'],
resources: [
`${bucket.bucketArn}/*`
],
// v2 conversion, previously with v1 this was [new iam.Anyone]
principals: [new iam.AnyPrincipal()],
})
// Add the policy to bucket
bucket.addToResourcePolicy(bucketPolicy);
}
}
Is there any additional policy I have to add on? This is the first time I am using TypeScript to create a bucket that I can then upload my React example site to. I feel as if something is missing, when I upload the content to the bucket, it updates and I have no problem logging into my AWS repository.
What am I missing?
I have deployed a react project to github and when viewing it with github pages . I'm using i18next for different translations for my web app . When I run my app through localhost the locales folder is accesed and translates the content of my app properly . However when deployed with github pages I get the errors :
WARNING:
i18next::backendConnector: loading namespace translation for language en failed failed loading /locales/en/translation.json
ERROR :
request.js:60 GET https://user.github.io/locales/en/translation.json 404
So I cannot access my translations inside my locales folder .
My folder structure (I have folder inside for more langs other than english in same level ) : public > locales > en > translation.json
the i18next.js from the docs located in :
src > i18n.js
with code :
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
// don't want to use this?
// have a look at the Quick start guide
// for passing in lng and translations on init
const Languages = ['en' , 'gr']; //the languages I want
i18n
// load translation using http -> see /public/locales (i.e. https://github.com/i18next/react-i18next/tree/master/example/react/public/locales)
// learn more: https://github.com/i18next/i18next-http-backend
.use(Backend)
// detect user language
// learn more: https://github.com/i18next/i18next-browser-languageDetector
.use(LanguageDetector)
// pass the i18n instance to react-i18next.
.use(initReactI18next)
// init i18next
// for all options read: https://www.i18next.com/overview/configuration-options
.init({
fallbackLng: 'en',
debug: true,
whitelist:Languages,
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
}
});
export default i18n;
I would appreciate your help
For deploying on gh-pages you need to adapt the loadPath where the json are hosted check this
Hope this work!
I am looking through next.js documentation and trying to understand what the suggested approach is for setting URLs that change in different environments. Mostly, I want to ensure that I'm pointing backend URLs correctly in development versus production.
I suppose you can create a constants configuration file, but is there a supported, best practice for this?
Open next.config.js and add publicRuntimeConfig config with your constants:
module.exports = {
publicRuntimeConfig: {
// Will be available on both server and client
yourKey: 'your-value'
},
}
you can call it from another .js file like this
import getConfig from 'next/config'
const { publicRuntimeConfig } = getConfig()
console.log(publicRuntimeConfig.yourKey)
or even call it from view like this
${publicRuntimeConfig.yourKey}
You can configure your next app using next-runtime-dotenv, it allows you to specify serverOnly / clientOnly values using next's runtime config.
Then in some component
import getConfig from 'next/config'
const {
publicRuntimeConfig: {MY_API_URL}, // Available both client and server side
serverRuntimeConfig: {GITHUB_TOKEN} // Only available server side
} = getConfig()
function HomePage() {
// Will display the variable on the server’s console
// Will display undefined into the browser’s console
console.log(GITHUB_TOKEN)
return (
<div>
My API URL is {MY_API_URL}
</div>
)
}
export default HomePage
If you don't need this separation, you can use dotenv lib to load your .env file, and configure Next's env property with it.
// next.config.js
require('dotenv').config()
module.exports = {
env: {
// Reference a variable that was defined in the .env file and make it available at Build Time
TEST_VAR: process.env.TEST_VAR,
},
}
Check this with-dotenv example.
I'm working on an angular app using play framework for my rest-services. Everything in the public folder is an angular app (stylesheets, javascripts, images and html). I want every request that is not for something in the stylesheets, javascripts, templates or images folder to be routed to the index.html page. This is so that angular routing can take over from there...
As a side note i can mention that I am going to place every restservice under /services/ which links to my own java controllers.
Is it possible in play framework 2.3.4 to define a route that catches all without having to use the matching elements?
This is my route defs so far:
GET / controllers.Assets.at(path="/public", file="index.html")
GET /stylesheets/*file controllers.Assets.at(path="/public/stylesheets", file)
GET /javascripts/*file controllers.Assets.at(path="/public/javascripts", file)
GET /templates/*file controllers.Assets.at(path="/public/templates", file)
GET /images/*file controllers.Assets.at(path="/public/images", file)
#this line fails
GET /* controllers.Assets.at(path="/public", file="index.html")
It's not possible to omit usage of matching elements but you can route a client via controller. The route definition looks like this:
GET /*path controllers.Application.matchAll(path)
And the corresponding controller can be implemented as follows:
public class Application extends Controller {
public static Result matchAll(String path) {
return redirect(controllers.routes.Assets.at("index.html"));
}
}
Update
If you don't want to redirect a client you can return a static resource as a stream. In this case a response MIME type is required.
public class Application extends Controller {
public static Result matchAll(String path) {
return ok(Application.class.getResourceAsStream("/public/index.html")).as("text/html");
}
}
For this task you can use onHandlerNotFound in Global class which will render some page without redirect:
import play.*;
import play.mvc.*;
import play.mvc.Http.*;
import play.libs.F.*;
import static play.mvc.Results.*;
public class Global extends GlobalSettings {
public Promise<Result> onHandlerNotFound(RequestHeader request) {
return Promise.<Result>pure(notFound(
views.html.notFoundPage.render(request.uri())
));
}
}
Answer for scala developers using playframework :)
Similar to above one about creating controller which will accept parameters and then omit them.
Example routing:
GET / controllers.Assets.at(path="/public", file="index.html")
GET /*ignoredPath ui.controller.AssetsWithIgnoredWildcard.at(path="/public", file="index.html", ignoredPath: String)
controller with assets injected by framework:
class AssetsWithIgnoredWildcard #Inject() (assets: Assets) {
def at(
path: String,
file: String,
wildcardValueToIgnore: String,
aggressiveCaching: Boolean = false): Action[AnyContent] = {
assets.at(path, file, aggressiveCaching)
}
}