NodeJS email-templates i18n localization - node.js

I have an issue with the localization of the pug templates combined with i18n. The language keeps rolling back to "en" language, but I've set the locale: 'sl' in the send() function, this is from the documentation of the email-templates.
Here is my code in typescript:
import * as path from 'path';
import Email = require("email-templates");
import { transporter } from '../mailerConnection';
import { I18n } from 'i18n';
export async function sendOutActivationEmail() {
const i18n = new I18n();
i18n.configure({
locales: ['en', 'sl'],
directory: path.join(__dirname, '../../locales'),
register: global
});
const email = new Email({
message: {
from: '"test" <noreplay#test.com>'
},
// uncomment below to send emails in development/test env:
//send: true,
transport: transporter,
i18n: i18n
});
email
.send({
template: path.join(__dirname, '../templates', 'activation'),
message: {
to: 'test#gmail.com'
},
locals: {
locale: 'sl',
name: 'Test'
}
})
.then(console.log)
.catch(console.error);
}
sendOutActivationEmail().catch(console.error);
Here is html.pug template:
p= __('message')
Here is en.json:
{
"message": "message1"
}
Here is sl.json:
{
"message": "messageSLO"
}
Here is the link to email-templates localization documentation: https://www.npmjs.com/package/email-templates#localization
What am I doing wrong that the functions doesn't switch to "sl" language? Thanks...

email-templates does not seem to document how the i18n object needs to look like, but probably you need to pass there somewhere the appropriate translations…
Alternatively, this looks more promising: https://dev.to/adrai/how-does-server-side-internationalization-i18n-look-like-5f4c#email

Actually they use extension of the default i18n package is ladjs/i18n so the object that you pass to the email-template needs to be in different shape.
I solved my issue using the code below:
const email = new Email({
message: {
from: '"Test" <noreplay#test.com>'
},
// uncomment below to send emails in development/test env:
//send: true,
transport: transporter,
i18n: {
locales: ['en', 'sl'],
directory: path.join(__dirname, '../../locales'),
defaultLocale: 'en'
}
});

Related

i18next - Loading translations from a JSON file

I'm trying to load translations from a JSON file using i18next library on Node. The path of the JSON file points to the correct location.
I'm getting the following error:
i18next::translator: missingKey en translation test test
import i18next from 'i18next';
import Backend from 'i18next-fs-backend';
const instance = i18next.use(Backend).createInstance({
lng: config.language,
debug: true,
fallbackLng: 'en',
initImmediate: false,
backend: {
loadPath: join(__dirname, `${config.language}.json`),
},
}, (error, t) => {
console.log(t('foo'));
});
JSON file:
{
"foo": "bar"
}
Specifying the translations directly in createInstance using resources property works perfectly.
I tried everything I could think of, with no success.
Found the solution!
import i18next from 'i18next';
import Backend from 'i18next-fs-backend';
const instance = i18next.use(Backend).createInstance();
instance.init({
lng: config.language,
debug: true,
fallbackLng: 'en',
initImmediate: false,
backend: {
loadPath: join(__dirname, `${config.language}.json`),
},
}, (error, t) => {
console.log(t('foo'));
});

vite dev server execute middleware before all other middleware

With vue-cli it was possible to configure webpack devServer.before function like this:
devServer: {
before(app) {
app.get('/apiUrl', (req, res) => res.send(process.env.API_URL))
}
},
How is it possible to configure Vite dev server to obtain the same behavior?
(I tried with the proxy option but it does not work.)
According to this github issue, environment variables are not accessible in file vite.config.js (neither in vite.config.ts). However, the discussion in this issue also mentions a workaround that you can use in this file:
import { defineConfig, loadEnv } from 'vite'
import vue from '#vitejs/plugin-vue'
export default defineConfig(({mode}) => {
const env = loadEnv(mode, process.cwd());
return {
plugins: [
vue(),
],
server: {
proxy: {
'^/apiUrl': {
target: env.VITE_API_TARGET,
changeOrigin: true,
}
}
},
}
})
Note that the variable name must start with VITE_ for this to work.

Vue Website Returns "Cannot Get /path" On All Pages EXCEPT Index

I am using Vue on Node.js to host my website on an AWS EC2 instance. I dont have an index node.js file, just the vue-router file. I use AWS CloudFront to bind my certificate to my traffic. The problem is that everytime i access the site through the server's link, the site works perfectly, but whenever i access it through the cloud-front link, only the index of the website will show up. No /about or /contact; instead it returns Cannot GET /about.
My Router:
import Vue from 'vue';
import Router from 'vue-router';
import VueCookies from 'vue-cookies';
import Home from './views/Home.vue';
import NotFound from './views/NotFound.vue';
Vue.use(Router);
Vue.use(VueCookies);
VueCookies.config('7d');
VueCookies.set('theme', 'default');
VueCookies.set('unique', Date.now());
VueCookies.set('rwapi-uuid', `v3-${Date.now()}-x9k0`)
export default new Router({
mode: 'history',
routes: [
{ path: '/', name: 'INDEX', component: Home },
{ path: '/about/', name: 'ABOUT', component() { return import('./views/About.vue'); } },
{ path: '/portfolio', name: 'PORTFOLIO', component() { return import('./views/Port.vue'); } },
{ path: '/contact', name: 'CONTACT', component() { return import('./views/Contact.vue'); } },
{ path: '/login', name: 'LOGIN', component() { return import('./views/Login.vue'); } },
{ path: '/404', component: NotFound },
{ path: '*', redirect: '/404' },
],
});
I have already tried to add the historyApiFallback: true to my webpack config but it had no effect.
According to Vue Router's documentation, when using your router in history mode, your webserver requires additional configuration.
I don't exactly know how do EC2 instances work, but if you don't have a webserver proxying all your requests to index.html, Vue-router will not be able to handle the other requests.

How to structure a Vue 2.0 app for server-rendered lazy routes?

I attempted to modify vue-hackernews-2.0 to support lazy-loaded routes using Webpack's code-splitting feature as per instructions found at these links:
https://router.vuejs.org/en/advanced/lazy-loading.html
http://vuejs.org/guide/components.html#Async-Components
However, I ran into some issues. When I loaded the app in the browser, all suggested variations of syntax triggered Module not found errors on the server-side when attempting to load in the server-side chunks.
Given this wrapper around the code-split points in router.js...
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
// INSERT CODE-SPLIT POINT SYNTAXES HERE (they are below)
export default new Router({
mode: 'history',
routes: [{
path: '/',
component: Home
}, {
path: '/foo',
component: Foo
}]
})
All of these variations of syntax threw the Module not found error:
Variation 1:
const Home = () => System.import('./views/Home.vue')
const Foo = () => System.import('./views/Foo.vue')
Variation 2:
const Home = (resolve) => require(['./views/Home.vue'], resolve)
const Foo = (resolve) => require(['./views/Foo.vue'], resolve)
Variation 3:
const Home = (resolve) => {
require.ensure(['./views/Home.vue'], () => {
resolve(require('./views/Home.vue'))
})
}
const Foo = (resolve) => {
require.ensure(['./views/Foo.vue'], () => {
resolve(require('./views/Foo.vue'))
})
}
The error message was always along the lines of:
(note: this error is adapted from a small reproduction I made of the issue, not from the hackernews example)
Error: Cannot find module './0.server.js'
at Function.Module._resolveFilename (module.js:440:15)
at Function.Module._load (module.js:388:25)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
at Function.requireEnsure [as e] (__vue_ssr_bundle__:42:25)
at Home (__vue_ssr_bundle__:152:30)
at /Users/razorbeard/projects/vue-2-ssr/node_modules/vue-router/dist/vue-router.js:1421:19
at iterator (/Users/razorbeard/projects/vue-2-ssr/node_modules/vue-router/dist/vue-router.js:1277:5)
at step (/Users/razorbeard/projects/vue-2-ssr/node_modules/vue-router/dist/vue-router.js:1213:9)
at step (/Users/razorbeard/projects/vue-2-ssr/node_modules/vue-router/dist/vue-router.js:1217:9)
I tried adapting my code to use the suggestions offered at Server-side react with webpack 2 System.import, but those did not work either.
I read a post that described configuring a build-time global variable using Webpack's DefinePlugin that allowed me to inspect whether the code was running on the server or on the client - this allows me to code-split on the client, but just bundle everything in on the server.
In the server webpack config:
{
...
plugins: [
new webpack.DefinePlugin({
BROWSER_BUILD: false
})
]
...
}
In the client webpack config:
{
...
plugins: [
new webpack.DefinePlugin({
BROWSER_BUILD: true
})
]
...
}
Then, in the same wrapper-snippet as above for the router.js file, I used this variation of syntax:
const Home = BROWSER_BUILD ? () => System.import('./views/Home.vue') : require('./views/Home.vue')
const Foo = BROWSER_BUILD ? () => System.import('./views/Foo.vue') : require('./views/Foo.vue')
This made rendering work - partially. Navigating directly to the app in the browser (and respective routes) server-rendered the correct UI. Clicking around, vue-router's client-side logic took me to the right UI. Everything seemed hunky-dory - until I opened DevTools:
The same issue also occurs if a module is loaded lazily as a subcomponent of a route:
<template>
<div class="page">
<heading></heading>
</div>
</template>
<script>
const Heading = BROWSER_BUILD ? () => System.import('./Heading.vue') : require('./Heading.vue')
export default {
components: {
Heading
}
}
</script>
I tried asking for some help in the official Vue forum, but came up empty: http://forum.vuejs.org/t/2-0-help-needed-with-server-rendered-lazy-routes/906
Thinking this might be a bug with vue-router, I opened an issue there: https://github.com/vuejs/vue-router/issues/820
Unfortunately, I wasn't able to find a solution.
So, I put together a small repo that reproduces the issue: https://github.com/declandewet/vue2-ssr-lazy-error
I have a hunch that the actual problem might be coming from https://www.npmjs.com/package/vue-server-renderer.
I'm really stuck on this and am used to how easy it is to do in react - and would really appreciate any help/tips/direction towards a solution!
Here is the webpack config from the reproduction repo for convenience:
import fs from 'fs'
import path from 'path'
import webpack from 'webpack'
import validate from 'webpack2-validator'
import { dependencies } from './package.json'
let babelConfig = JSON.parse(fs.readFileSync('./.babelrc'))
/* turn off modules in es2015 preset to enable tree-shaking
(this is on in babelrc because setting it otherwise causes issues with
this config file) */
babelConfig.presets = babelConfig.presets.map(
(preset) => preset === 'es2015' ? ['es2015', { modules: false }] : preset
)
const babelOpts = {
...babelConfig,
babelrc: false,
cacheDirectory: 'babel_cache'
}
const SHARED_CONFIG = {
devtool: 'source-map',
module: {
loaders: [{
test: /\.vue$/,
loader: 'vue'
}, {
test: /\.js$/,
loader: 'babel',
exclude: 'node_modules',
query: babelOpts
}]
},
resolve: {
modules: [
path.join(__dirname, './src'),
'node_modules'
]
}
}
const SERVER_CONFIG = validate({
...SHARED_CONFIG,
target: 'node',
entry: {
server: './src/server.js',
renderer: './src/renderer.js'
},
output: {
path: path.join(__dirname, './dist'),
filename: '[name].js',
chunkFilename: '[id].server.js',
libraryTarget: 'commonjs2'
},
plugins: [
new webpack.DefinePlugin({
BROWSER_BUILD: false,
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),
new webpack.BannerPlugin({
banner: 'require("source-map-support").install();',
raw: true,
entryOnly: false
})
],
externals: Object.keys(dependencies)
})
const CLIENT_CONFIG = validate({
...SHARED_CONFIG,
entry: {
app: './src/client.js',
vendor: ['vue']
},
output: {
path: path.join(__dirname, './dist/assets'),
publicPath: '/',
filename: 'bundle.js'
},
plugins: [
new webpack.DefinePlugin({
BROWSER_BUILD: true,
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: 'vendor.js'
})
]
})
export default [SERVER_CONFIG, CLIENT_CONFIG]
EDIT: Noticing that in React, we use match on the client to get the right route config for the current view, I decided to inspect what components were getting matched using app.$router.getMatchedComponents() and found something interesting:
Server Entry:
import app from './app'
export default (context) => {
// using app.$router instead of importing router itself works
// (not sure why the hacker-news example imports the router module instead...)
app.$router.push(context.url)
const components = app.$router.getMatchedComponents()
console.log('server-side', components)
return Promise.all(components.map((component) => component))
.then(() => app)
}
When navigating to the home page, this logs to the terminal:
server-side [ { __file: '/Users/razorbeard/projects/vue-2-ssr/src/views/Home.vue',
render: [Function],
staticRenderFns: [ [Function] ] } ]
Client Entry:
import app from './app'
const components = app.$router.getMatchedComponents()
console.log('client-side', components)
// kickoff client-side hydration
Promise.all(components.map((component) => Promise.resolve(component)))
.then(() => app.$mount('#app'))
When navigating to the home page, this logs to the devtools console:
client-side []
As you can see, no components are getting matched on the client side.

hapi-auth-cookie failing to load session strategy

There's not many examples out there for hapi and its auth-cookie plugin but here's what I have so far in an attempt to secure a route. Note, most of the examples I've seen are using an older version of hapi which doesn't seem to quite apply to this situation and im hoping im just missing something simple:
var Hapi = require('hapi');
var Mongoose = require('mongoose');
Mongoose.connect('mongodb://localhost/rfmproducetogo');
var server = new Hapi.Server(8080, "localhost");
server.pack.register([{
plugin: require("lout")
}, {
plugin: require('hapi-auth-cookie')
}, {
plugin: require("./plugins/togo")
}, {
plugin: require("./plugins/auth")
}], function(err) {
if (err) throw err;
server.auth.strategy('session', 'cookie', {
password: 'shhasecret',
cookie: 'wtfisthisfor',
isSecure: false,
redirectTo: false
});
server.start(function() {
console.log("hapi server started # " + server.info.uri);
});
});
And in my togo plugin I have this route setup to use the session
exports.create = function(plugin) {
plugin.route({
method: 'POST',
path: '/togo/add',
handler: function(request, reply) {
produce = new Produce();
produce.label = request.payload.label;
produce.price = request.payload.price;
produce.uom = request.payload.uom;
produce.category = request.payload.category;
produce.save(function(err) {
if (!err) {
reply(produce).created('/togo/' + produce._id);
} else {
reply(err);
}
});
},
config: {
auth: 'session'
}
});
};
The error im seeing is this:
/home/adam/Projects/bushhog/node_modules/hapi/node_modules/hoek/lib/index.js:421
throw new Error(msgs.join(' ') || 'Unknown error');
^
Error: Unknown authentication strategy: session in path: /togo/add
at Object.exports.assert (/home/adam/Projects/bushhog/node_modules/hapi/node_modules/hoek/lib/index.js:421:11)
at /home/adam/Projects/bushhog/node_modules/hapi/lib/auth.js:123:14
at Array.forEach (native)
at internals.Auth._setupRoute (/home/adam/Projects/bushhog/node_modules/hapi/lib/auth.js:121:24)
at new module.exports.internals.Route (/home/adam/Projects/bushhog/node_modules/hapi/lib/route.js:118:43)
at /home/adam/Projects/bushhog/node_modules/hapi/lib/router.js:110:25
at Array.forEach (native)
at /home/adam/Projects/bushhog/node_modules/hapi/lib/router.js:107:17
at Array.forEach (native)
at internals.Router.add (/home/adam/Projects/bushhog/node_modules/hapi/lib/router.js:104:13)
Running node 0.10.28, hapijs 6.x, hapi-auth-cookie 1.02
this issue occurs when you try to use an authentication strategy before it's actually available.
You're already following a good application setup by splitting the functionality into individual, small plugins with a given scope.
UPDATE: here's a dedicated tutorial for that problem, how to fix „unknown authentication strategy“
A good way to set up authentication and your plugins that rely on authentication is to create an extra "auth plugin" that adds your desired strategies and can be used as a dependency in your other plugins.
hapi auth plugin example
exports.register = function (server, options, next) {
// declare/register dependencies
server.register(require('hapi-auth-cookie'), err => {
/**
* Register authentication strategies to hapi server
*
* We’re using hapi-auth-cookie plugin to store user information on
* client side to remember user data on every website visit
*
* For sure, we could and will add more authentication strategies.
* What’s next: JWT (we highly welcome pull requests to add JWT functionality!)
*/
server.auth.strategy('session', 'cookie', {
password: 'ThisIsASecretPasswordThisIsASecretPassword',
cookie: 'hapi-rethink-dash',
redirectTo: '/login',
isSecure: false
});
server.log('info', 'Plugin registered: cookie authentication with strategy »session«')
next()
})
}
exports.register.attributes = {
name: 'authentication',
version: '1.0.0'
}
In your /plugins/togo you set the authentication plugin as a dependency (with server.dependency([array-of-deps])) which means hapi registers the auth plugin first and the depending ones afterwards.
You register your plugins like this:
server.register([{
plugin: require('./plugins/authentication')
}, {
plugin: require("./plugins/togo")
}], function(err) {
// handle callback
})
Check hapi-rethinkdb-dash for a detailed example.
Hope that helps!
keep in mind if you use server.dependency inside a plugin like Marcus Poehls did, you also need to register that dependency
server.register([{
plugin: require('hapi-auth-cookie')
},{
plugin: require('./plugins/authentication')
}, {
plugin: require("./plugins/togo")
}], function(err) {
// handle callback
})

Resources