How to change config variable based on the url - node.js

I have two websites, websiteEN and websiteDE.
They are both hosted on EC2 on their own instance.
their urls are : website.en and website.de
they use their own database websiteENDB and websiteDEDB.
I a currently using environment variables on AWS for their database.
To save money, I would like to host the two websites on the same instance.
I would need to get the database name from the url which is used to navigate the website.
How can I get the url with an express server and pass it to my config variable ?
EDIT :
Let's say for example that I have config.websiteDB = defaultDB
If a user is visiting the website from website.de, I would like to have config.websiteDB = websiteDEDB and if she is visiting the website from website.en, config.websiteDB = websiteENDB

Here is how we solved it.
We used,
https://github.com/mashpie/i18n-node
Also, you can use the same html template files and just have a different content for different languages.
Based on the language received from browser, you can choose appropriate database.
Hope it helps.
EDIT1:
If you check below, you can set your locales based on cookies, querystring parameter, fallback when a language content is not available etc.,
i18n.configure({
// setup some locales - other locales default to en silently
locales:['en', 'de'],
// fall back from Dutch to German
fallbacks:{'nl': 'de'},
// you may alter a site wide default locale
defaultLocale: 'de',
// sets a custom cookie name to parse locale settings from - defaults to NULL
cookie: 'yourcookiename',
// query parameter to switch locale (ie. /home?lang=ch) - defaults to NULL
queryParameter: 'lang',
// where to store json files - defaults to './locales' relative to modules directory
directory: './mylocales',
To set a cookie to desired language,
res.cookie('yourcookiename', 'de', { maxAge: 900000, httpOnly: true });
You can also use querystring parameters
/home?lang=ch
where lang is defined as a locale config parameter.

Related

Changing Express constant based on URL (ie localhost vs production)

I'm fairly new to node and express...
I have a constant I set in my Node/Express application for "Domain". I'm constantly switching between localhost and the actual url when I switch between development and production.
I'm trying to figure out how I can automatically test the URL so that when the code is read on the server (ie actual domain url vs localhost) that it sets the proper domain url.
Here is my code:
function define(name, value) {
Object.defineProperty(exports, name, {
value: value,
enumerable: true
});
}
define("DOMAIN", "http://www.actual_domain.com");
// define("DOMAIN", "http://localhost:3000");
Anyone have a simple solution for this?
Thanks!!
there is many solutions for this, but usually this is done by environment variables, depends on your platform, but, in Linux systems, you do the following in your shell
export ENV_URL="http://www.example.com"
and to make sure its exported successfully
echo $ENV_URL
and in your code you do
const base_url = process.env.ENV_URL || "http://www.default.com";
in your local machine you set the ENV_URL to localhost or whatever you prefer, and in your server you set it to your actual URL.
or you could simply have many configuration files and you can determine the appropriate one by the environemnt variable like
export ENV=PROD
and in your code you can load the prod configuration file that contains your environment configurations.
The de facto way to do this sort of thing is through environment variables. Have a look at 12factor.net for a load of best practices, but in general you want to put differences in the environment into environment variables, then read those variables at runtime.

Parse Server Config Options In Azure

I've installed a parse.com server in Azure. All is working well with the initial setup.
I now want to lock down the server with a few of the "Advanced Options" as annotated on the Parse Server Github page.
I understand that I do these in the App Settings in Azure a la the below:
Namely, sessionLength should be visible following a server restart? However this is not the case as I still get 1 year sessions for newly logged in users. Am I filling in the details incorrectly, is there an error with Azure & Parse Server, or am I doing this completely wrong?
Im not sure if it should be SESSION_LENGTH. You would need to check to see how its constructed in the index.js.
Update:
You could try Edit the config file and pass extra params like this:
sessionLength : process.env.SESSION_LENGTH || 31536000 //Set to what you need
enableAnonymousUsers : process.env.ENABLE_ANON_USERS || false,
allowClientClassCreation: process.env.CLIENT_CLASS_CREATION || false,
github.com/mamaso/parse-server-azure-config
Look at the ENV variables listed : https://github.com/ParsePlatform/parse-server/blob/master/src/cli/definitions/parse-server.js
OR
Alternative you could update the session value on log-in or signup via a cloud code function.

Serve out swagger-ui from nodejs/express project

I would like to use the swagger-ui dist 'as-is'...well almost as-is.
Pulled down the latest release from github (2.0.24) and stuck it in a folder in my app. I then server it out statically with express:
app.use('/swagger', express.static('./node_modules/swagger-ui/dist'));
That works as expected when I go to:
https://mydomain.com/swagger
However I want to populate the url field to my swagger json dynamically. IE I may deploy to different domains:
https://mydomain.com/api-docs
https://otherdomain.com/api-docs
And when I visit:
https://mydomain.com/swagger
https://otherdomain.com/swagger
I would like to dynamically set the url.
Is that possible?
Assuming the /api-docs (or swagger.json) are always on the same path, and only the domain changes, you can set the url parameter of the SwaggerUi object to "/path/to/api-docs" or "/path/to/swagger.json"instead of a full URL. That would make the UI load that path as relative to the domain the UI is hosted on.
For reference, I'm leaving the original answer as well, as it may prove useful in some cases.
You can use the url parameter to set the URL the UI should load.
That is, if you're hosting it under https://mydomain.com/swagger you can use https://mydomain.com/swagger?url=https://mydomain.com/api-docs and https://mydomain.com/swagger?https://otherdomain.com/api-docs to point at the different locations.
However, as far as I know, this functionality is only available at the current alpha version (which should be stable enough) and not with 2.0.24 that you use (though it's worth testing).
Another method would be to use the swagger-ui middleware located in the swagger-tool.
let swaggerUi = require('../node_modules/swagger-tools/middleware/swagger-ui');
app.use(swaggerUi(config.swagger));
The variable config.swagger contains the swagger.yaml or swagger.json. I have in my setting
let config = {
appRoot: __dirname,
swagger: require('./api/swagger/swagger.js')
};
Note: I am using the require('swagger-express-mw') module
You could try with this on index.html file of the swagger-ui... It works for me.
if (url && url.length > 1) {
url = decodeURIComponent(url[1]);
} else {
url = window.location.origin + "/path/to/swagger.json";
}

Where to find express.js settings

I'm almost ashamed to ask this, but where can I find information about the settings for express.js? According to the documentation I can use app.set(name, setting) to assign setting name to setting, however I can't find anywhere which settings there are and how they work.
You can find it here:
http://expressjs.com/api.html#app-settings
settings
The following settings are provided to alter how Express will behave:
env Environment mode, defaults to process.env.NODE_ENV or "development"
trust proxy Enables reverse proxy support, disabled by default
jsonp callback name Changes the default callback name of ?callback=
json replacer JSON replacer callback, null by default
json spaces JSON response spaces for formatting, defaults to 2 in development, 0 in production
case sensitive routing Enable case sensitivity, disabled by default, treating "/Foo" and "/foo" as the same
strict routing Enable strict routing, by default "/foo" and "/foo/" are treated the same by the router
view cache Enables view template compilation caching, enabled in production by default
view engine The default engine extension to use when omitted
views The view directory path

Where would I get the base URI In my ServiceStack markdown page?

I am looking to serve an image from my root path test.com/some.png but this markdown page may be displayed on [Post]test.com/Item or [Put]test.com/Item/123 So I am looking for a way to get the base URI to form the image link.
You can use the literal text ~/ inside a Markdown page gets converted to a virtual path.
This literal is registered on start-up from the global EndpointHostConfig.MarkdownReplaceTokens property which is assigned the appHost.Config.WebHostUrl property:
this.MarkdownReplaceTokens["~/"] = appHost.Config.WebHostUrl.WithTrailingSlash();
Since it's difficult for an ASP.NET framework to determine the url its hosted at (i.e. without a request) you need to specify the preferred url you wan to use in your config. Here's an example from the servicestack.net/docs/ - ServiceStack's markdown Docs project:
SetConfig(new EndpointHostConfig {
WebHostUrl = baseUrl, //replaces ~/ with Url
MarkdownBaseType = typeof(CustomMarkdownPage),
});
Otherwise inside your service you can use base.Request or base.RequestContext.Get<IHttpRequest>() to get information about the incoming Request as well as (HttpRequest)base.Request.OriginalRequest to get the underlying ASP.NET Request object.

Resources