Change nuxt-i18n locale with cookie on site load - internationalization

I've two locale; "fa" and "en" with fa being default. I've tried to change it with the following code block both on nuxtServerInit and fetch hook of layout but it still revert back to my default locale and gives me json.parse error on route change.
// using "nuxt": "^2.15.8" , "#nuxtjs/i18n": "^7.2.0" , "#nuxtjs/universal-storage": "^0.5.9" , "#nuxtjs/vuetify": "^1.12.3"
async fetch(){
let locale = this.$storage.getCookie('localeLang')
if(!!locale){
await this.$i18n.setLocale(locale)
this.$vuetify.rtl = this.$i18n.localeProperties.dir === 'rtl'
this.$storage.setCookie('localeLang', locale, {maxAge: 315360000})
}
}
When using in fetch hook i can see for a moment that it's in en then revert back to fa . but the htmlAttr of meta are set according to en locale (which has been set on cookie)
So what should I do? Any idea?
// nuxt.config.js
i18n: {
baseURL: process.env.DEFAULT_BASE_URL,
locales:[
{
code: 'fa',
iso: 'fa-IR',
file: 'fa.js',
currency: {name:'تومان', sign:'ت'},
dir: 'rtl',
name: 'فارسی',
initial: 'FA',
},
{
code: 'en',
iso: 'en-US',
file: 'en.js',
currency: {name:'Dollar', sign:'$'},
dir: 'ltr',
name: 'English',
initial: 'EN',
},
],
defaultLocale: 'fa',
strategy: 'no_prefix',
lazy: true,
langDir: '~/locale/lang/',
detectBrowserLanguage: false,
// vueI18n: '~/plugins/vue-i18n.js',
},

Related

Strapi not uploading pictures to Cloudinary

UPDATE: I installed Strapi version 3.6.3 and it works well
Strapi - Clouinary connection do not work for me. So I'm uploading pictures to Stapi, but they don't appear in Clouinary.
In config folder I created file plugins.js with following content:
module.exports = ({
env
}) => ({
// ...
upload: {
provider: 'cloudinary',
providerOptions: {
cloud_name: env('CLOUDINARY_NAME'),
api_key: env('CLOUDINARY_KEY'),
api_secret: env('CLOUDINARY_SECRET'),
},
},
// ...
});
I have installed npm i strapi-provider-upload-cloudinary
then changed file .env to
PORT=1337
CLOUDINARY_NAME="***"
CLOUDINARY_KEY="***"
CLOUDINARY_SECRET="***"```
Actually automatically following code added automatically:
```JWT_SECRET=*********
API_TOKEN_SALT=*********
JWT_SECRET=*********
What could be a problem?
should CLOUDINARY_SECRET be in "quotes"? or in 'quotes' or without quotes?
Terminal output after adding image is following:
http://localhost:1337
[2021-12-07 02:10:14.702] http: POST /upload (261 ms) 200
[2021-12-07 02:10:14.744] http: GET /upload/files?sort=updatedAt:DESC&page=1&pageSize=10 (24 ms) 200
[2021-12-07 02:10:14.758] http: GET /uploads/thumbnail_Screenshot_2021_11_26_130226_11a95e81ea.png?width=1504&height=1258 (4 ms) 200
All permissions seems to be set...
Also created extentions/upload/config/setting.json with the following content:
"provider": "cloudinary",
"providerOptions": { "cloud_name":"devert0mt",
"api_key": "***",
"api_secret":"***"
}
}{
"provider": "cloudinary",
"providerOptions": { "cloud_name":"devert0mt",
"api_key": "***",
"api_secret":"***"
}
}```
If you want to use the latest version of Strapi, v.4 and above, you need to change strapi provider package to this one:
npm install #strapi/provider-upload-cloudinary --save
Then, you need to update your plugins.js file in config/plugins.js to the following ( Be aware that it has a slightly different structure than the previous package - everything is placed in config object, instead of upload like it was on a previous version):
module.exports = ({ env }) => ({
// ...
upload: {
config: {
provider: 'cloudinary',
providerOptions: {
cloud_name: env('CLOUDINARY_NAME'),
api_key: env('CLOUDINARY_KEY'),
api_secret: env('CLOUDINARY_SECRET'),
},
actionOptions: {
upload: {},
delete: {},
},
},
},
// ...
});
Also, if you are having issues with properly rendering your images on your Strapi dashboard you can update middlewares.js in config/middlewares.js:
Instead of 'strapi::security' in module.exports, paste this:
// ...
{
name: 'strapi::security',
config: {
contentSecurityPolicy: {
useDefaults: true,
directives: {
'connect-src': ["'self'", 'https:'],
'img-src': ["'self'", 'data:', 'blob:', 'res.cloudinary.com'],
'media-src': ["'self'", 'data:', 'blob:', 'res.cloudinary.com'],
upgradeInsecureRequests: null,
},
},
},
},
// ...

Routing in Serverless nuxt app not working

So I'm getting a routing problem whenever I use nuxt ssr with serverless. When I use either deploy to AWS lambda or use serverless-offline it generates the url prefixed with /{stage}, but nuxt can't seem to handle this and either throws 403, 404 or 500 errors because the routes to static files aren't prefixed with /{stage}.
I have tried adding {stage} to the public path on build, the results in a 404 because now the static file path needs to prefixed with another /{stage}. If I go directly to {stage}/{stage}/_nuxt/{file} it works.
build: {
publicPath: '/{stage}/_nuxt'
}
So looking around I found that I can update the router base to the below
router: {
base: '/{stage}'
}
but now the file only loads if its {stage}/{stage}/{stage}/_nuxt/{file} and removing the publicPath code above doesn't make it work either.
And this is for the static files, when it comes to the actual routes the homepage set at '/' either works but any other pages don't because the nuxt-links to them aren't prefixed with /{stage} or if I add the prefix to the base I get a Cannot GET / error when I visit /{stage}.
I have tried many different ways of doing this such as using express however I have had no luck and any tutorials that I found online are at least 2 years old and the github repos have the same problem. The closest thing I have found on stackoverflow that is somewhat similar to what I have is here but this is for a static site.
Anybody have any ideas? Below is the code for the serverless.yaml, handler.js, nuxt.js, nuxt.config.js.
Github Repo
serverless.yaml
service: nuxt-ssr-lambda
provider:
name: aws
runtime: nodejs12.x
stage: ${env:STAGE}
region: eu-west-1
lambdaHashingVersion: 20201221
environment:
NODE_ENV: ${env:STAGE}
apiGateway:
shouldStartNameWithService: true
functions:
nuxt:
handler: handler.nuxt
events:
- http: ANY /
- http: ANY /{proxy+}
plugins:
- serverless-apigw-binary
- serverless-dotenv-plugin
- serverless-offline
custom:
apigwBinary:
types:
- '*/*'
handler.js
const sls = require('serverless-http')
const binaryMimeTypes = require('./binaryMimeTypes')
const nuxt = require('./nuxt')
module.exports.nuxt = sls(nuxt, {
binary: binaryMimeTypes
})
nuxt.js
const { Nuxt } = require('nuxt')
const config = require('./nuxt.config.js')
const nuxt = new Nuxt({ ...config, dev: false })
module.exports = (req, res) =>
nuxt.ready().then(() => nuxt.server.app(req, res))
nuxt.config.js
module.exports = {
telemetry: false,
head: {
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: '' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
css: [
],
plugins: [
],
components: true,
buildModules: [
'#nuxtjs/tailwindcss',
],
modules: [
],
router: {
base: '/prod'
},
build: {
}
}
Are you passing it as
<p>Path: {{ $route.path }}</p>
<NuxtLink to="/">Back to Mountains</NuxtLink>
if Yes then it should work else try going with redirect('/{stage}/_nuxt')
for an if statement put this inside else , I think it should work.

ERR_TOO_MANY_REDIRECTS on vercel after deploying Nextjs App

I deployed my nextjs app to Vercel and it was a success.
I can see a preview of the website and even the log saying it works well.
But i try to access the website via the default Vercel domain :
https://tly-nextjs.vercel.app/
I get an ERR_TOO_MANY_REDIRECTS.
I do not have this problem locally.
I tried :
Disabling a language redirect that I use (/en for english folks, and / for french people).
Disabling the language detector of i18next.
But none of these solutions changed anything.
Any ideas ?
i18n.js file
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Cache from 'i18next-localstorage-cache';
import LanguageDetector from 'i18next-browser-languagedetector';
const fallbackLng = ['fr'];
const availableLanguages = ['fr', 'en'];
const en = require('./locales/en/common.json');
const fr = require('./locales/fr/common.json');
const options = {
order: ['querystring', 'navigator'],
lookupQuerystring: 'lng'
}
const cacheOptions = {
// turn on or off
enabled: true,
// prefix for stored languages
prefix: 'i18next_res_',
// expiration
expirationTime: 365*24*60*60*1000,
// language versions
//versions: {}
}
i18n
.use(Cache)
.use(initReactI18next)
.use(LanguageDetector)
.init({
cache: cacheOptions,
fallbackLng: fallbackLng,
debug: true,
detection: options,
supportedLngs: availableLanguages,
nonExplicitSupportedLngs: true,
resources: {
en: {translation: en},
fr: {translation: fr},
},
interpolation: {
escapeValue: false,
},
react: {
wait: true,
useSuspense: true,
},
});
export default i18n;
My change Language function :
const changeLanguageInHouse = (lang, bool) => {
setLoading(true);
i18next.changeLanguage(lang).then((t) => {
setLanguage(lang);
bake_cookie("langChoice", lang);
setLoading(false);
if (bool === true) {
var newUrl2 = (lang === "fr" ? "" : "/en") + asPath;
window.location.replace(newUrl2);
}
});
};
What happend at your server is following:
You enter https://tly-nextjs.vercel.app/ and it is redirected to /en with HTTP-Status-Code 307 (Temporary Redirect).
And /en redirect with 301 (Permanent Redirect) to /.
You can reproduce this by open the Browser-Dev-Tools and have a look at the Network Tab.
It might be, that you have some kind of url-rewriting activated at your server, which redirect everything to your domain-root.
Is there a public repo available for this? Here is how it worked for me.
Try changing the order of the locales and the default locale (not sure this helps, but it changed something for me. Undocumented if that is the case!)
So I put the default locale first (which is nl for me) in both the locales array and the domains array.
Let me know if that helps!
module.exports = {
i18n: {
localeDetection: false,
// These are all the locales you want to support in
// your application
locales: ['nl', 'en'],
// This is the default locale you want to be used when visiting
// a non-locale prefixed path e.g. `/hello`
defaultLocale: 'nl',
// This is a list of locale domains and the default locale they
// should handle (these are only required when setting up domain routing)
domains: [
{
domain: 'example.be',
defaultLocale: 'nl',
},
{
domain: 'example.com',
defaultLocale: 'en',
},
],
},
trailingSlash: true,
};
I changed all my getInitialProps to getServerSideProps
and realised I was doing a redirect on response :
res.writeHead(301, { Location: "/" })
I just delete it.
And now I don't have this endless redirect.
Doing this worked for me...
https://ardasevinc.tech/cloudflare-vercel-too-many-redirects
I think it's the actual solution to the cause of the problem rather than a bandage!

How do use Sass in Docusaurus v2?

I followed the instructions to use Sass in my Docusaurus v2 project, but I get the following error when I run yarn start:
Error: Cannot find module 'docusaurus-plugin-sass'
My config file is straight out of the box:
module.exports = {
title: '...',
tagline: '...',
url: '...',
baseUrl: '/',
favicon: 'img/favicon.ico',
organizationName: '...', // Usually your GitHub org/user name.
projectName: '...', // Usually your repo name.
themeConfig: {
navbar: {...},
footer: {...},
},
presets: [
[
'#docusaurus/preset-classic',
{
docs: {...},
blog: {...},
theme: {
customCss: require.resolve('./src/scss/index.scss'),
},
},
],
],
plugins: ['docusaurus-plugin-sass'],
};
Is this a bug or am I missing something?
Few things to check
Did you add docusaurus-plugin-sass to your package.json?
If you're using alpha.56, take note of the following change - https://github.com/facebook/docusaurus/releases/tag/v2.0.0-alpha.56
If you refer to modules (plugins) in your config file in a string form, you will need to replace them with require.resolve calls, for example:
- plugins: ['#docusaurus/plugin-google-analytics']
+ plugins: [require.resolve('#docusaurus/plugin-google-analytics')]

JSHint (r10): 'angular' is not defined

I have the following:
angular.module('test')
.controller('TestMenuController',
[
'$http',
'$scope',
'$resource',
'$state',
'os',
'us',
function (
$http,
$scope,
$resource,
$state,
os,
us) {
When I build this in VS2014 it gives me an error message saying:
JSHint (r10): 'angular' is not defined.
Can someone tell me how I can avoid this message coming up?
One way to tackle this is to modify your .jshintrc and set angular as one of the predefined variables, as Jayantha said.
.jshintrc would look like this:
{
"predef": ["angular"]
}
One approach would be adding 'angular' as a global variable in the config options,
or another by setting the config options 'jshintrc' path to .jshintrc
documentation (different ways to configure jshint options)
If you're using grunt..
//------------------------//
// jshint
//------------------------//
/**
* JSHint: configurations
* https://github.com/gruntjs/grunt-contrib-jshint
*/
jshint: {
options: {
jshintrc: '.jshintrc',
jshintignore: '.jshintignore',
reporter: require('jshint-stylish')
},
gruntfile: {
src: 'Gruntfile.js'
},
scripts: {
src: '<%= project.scripts %>/**/*.js'
},
all: [
'Gruntfile.js',
'<%= project.js %>/*.js',
'<%= project.scripts %>/**/*.js',
'test/**/*.js'
]
},
and in .jshintrc (at root dir) contains my following options
{
"curly" : true,
"eqeqeq" : true,
"undef" : true,
"jquery" : true,
// global variables
"globals": {
"angular" : false,
"jasmine" : false,
"$" : false,
"_" : false,
"module" : false,
"require" : false
}
}
Hope this helps.

Resources