How access environment variables from a Framework Components in Astro? - environment-variables

I'm working in a project using Astro and I am using a component with VUE. For this project I need to access some env vars.
I am able to access from the Astro templates, but I can't find a way to get in the VUE component. Is this possible?

There is no way to do this without exposing the environment variables.
To do this, we have to move the function to an endpoint of our API that runs on the server side and make a request to execute it safely.

You can expose the env var as data to the Vue component like so...
Vue 2
<script>
const { PUBLIC_ENV_HERE } = import.meta.env;
export default {
data() {
return {
PUBLIC_ENV_HERE,
};
},
};
</script>
Vue 3 with script setup
<script setup>
const { PUBLIC_ENV_HERE } = import.meta.env;
</script>
Remember to prefix client side variables with PUBLIC - see https://docs.astro.build/en/guides/environment-variables/ for more info.

Related

How the serve static html files with vaadin router

I have te following route configuration in my hilla app
router.setRoutes([
{path: '/', component: 'home-view'},
]);
this is works, but I need to publish some static html files. Not sure where to put the files and how to configure router to make them accessible with URL like /myfile.html?
already tried to put them in /frontend folder and add route, but does not work but creates a loop
{
path: '(.*)\.html',
action: (ctx, commands) => {
window.location.pathname = ctx.pathname;
}
}
Found it here How do I deliver static html pages with vaadin router (client side)?
The server is a Spring Boot server so any file you put inside src/main/resources/META-INF/resources is made available, e.g. if you create src/main/resources/META-INF/resources/myfile.html then you can access it as http://localhost:8080/myfile.html.
If you are just loading a static HTML page there is no need to configure the router for it. For a link you can add router-ignore so that router will not try to intercept it, e.g. `"

Handle url with .html extension in angular2 router?

We are working on a Angular2(created from angular-cli v1.0.0-beta.28.3) which connects to Salesforce via OAth's User-Agent Flow mechanism(https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_understanding_user_agent_oauth_flow.htm).
Here is the authentication code i've used in the code.
Here's the code which handles the callback after Authentication:
import { Component } from '#angular/core';
import { ForceService } from './force';
#Component({
template : ` `,
})
export class AuthComponent {
constructor(force : ForceService) {
var event = new CustomEvent("oauthCallback", {'detail': window.location.href});
window.opener.document.dispatchEvent(event);
window.close();
}
}
In Salesforce, we have something called Connected-App, where we configure the callback urls for the authentication. Callbacks url looks like below:
https://my.site.com/#/auth-callback. Angular2 router configuration uses useHash:true option as well.
Everything is working fine until the new requirement which needs only the callback url to point to something like this:
https://my.site.com/auth-callback.html
So the equivalent html code for above will be :
<html>
<script type="text/javascript">
var event = new CustomEvent("oauthCallback", {'detail': window.location.href});
window.opener.document.dispatchEvent(event);
window.close();
}
</script>
</html>
Problem, we face is after Authenticating, we are not able to access the access_token from the url and close the Authentication Window, since the routing is not properly redirecting to auth-callback.html. All we get is a blank screen with url changed to http://localhost:4200/#/access_token
Is there's a way to solve this issue without turning off useHash ?

Electron app: How do you use ipcRenderer.sendToHost()?

In the Electron documentation for the webview tag, the following example is given to show how to communicate between the renderer process and the web page hosted in the webview:
With sendToHost method and ipc-message event you can easily communicate between guest page and embedder page:
// In embedder page.
const webview = document.getElementById('foo')
webview.addEventListener('ipc-message', (event) => {
console.log(event.channel)
// Prints "pong"
})
webview.send('ping')
// In guest page.
const {ipcRenderer} = require('electron')
ipcRenderer.on('ping', () => {
ipcRenderer.sendToHost('pong')
})
However, in my guest web page (inside the webview), I get Uncaught ReferenceError: require is not defined when I try to require('electron'), as indicated in the docs.
Is there something else I need to do to be able to require the ipcRenderer module from the guest web page?
Electron version: 1.4.6
Note: I'm not sure if this is important or not, but the page running inside my webview is served from a local server. In my top-level page in the renderer process, I do something like: document.getElementById("webview").src = "http://localhost:1234/...";.
Edit: It looks like serving my web page from a local server does not change anything. I have the same error after trying with a static HTML file. It looks like the example in the docs simply doesn't work, or I'm understanding it wrong.
// Simple foo.html somewhere on my computer
<script>
const {ipcRenderer} = require('electron')
ipcRenderer.on('ping', () => {
ipcRenderer.sendToHost('pong')
})
</script>
// In embedder page, in renderer process
document.getElementById("webview").src = "file://path/to/foo.html";
Output from the embedded page (inside the webview):
Uncaught ReferenceError: require is not defined
EDIT
For security reasons, the preferred way to use require in renderer processes is to use preload to inject only the minimum node integration your page requires. See point 2) of Electron's security recommendations. A minimal example for ipcRenderer:
// main.ts
const mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: false,
preload: './preload.js'
}
})
mainWindow.loadURL('https://my-website.com')
// preload.js
const { ipcRenderer } = require('electron')
window.sendToElectron= function (channel) {
ipcRenderer.send(channel)
}
In your webpage you can now use window.sendToElectron("ping").
If you're using <webview> inside the renderer process, you can use <webview src="page.html" preload="./preload.js" /> to achieve the same result. So, that's what I would use to answer my original question, and inside preload.js I would inject a function that calls ipcRenderer.sendToHost("pong") in the global window.
Old answer (bad for security)
I had missed a vital point in the webview docs. To be able to call require from the page embedded inside the webview, you need to set the nodeintegration attribute on the webview tag:
<webview id="webview" nodeintegration />

Manage URL when debugging from Visual Studio 2015

I have an asp.net mvc site to which I've added some knockoutjs. The knockout code makes ajax request for data from the controllers e.g.
$.getJSON(BASE_URL + 'MyTasks/GetDataPage', { userKey: vm.UserKey, pageSize: pageSize }, function (returnedPayload) {
data = returnedPayload.filter(function (item) {
return JSON.stringify(item).toLowerCase().indexOf(ft) != -1;
});
self.setPagingData(data,page,pageSize);
The BASE_URL constant I set in the <head> of my layout razor page as follows:
<script type="text/javascript">
var BASE_URL = '/bamportal/';
</script>
All works fine when the website is deployed. However, when I run the website from VS by hitting F5 then I get a 404 such as:
http://localhost:49601/bamportal/MyTasks/GetDataPage?userKey=2&pageSize=50 Failed to load resource
If it had tried to address "http://localhost:49601/MyTasks/GetDataPage" (without the "/bamportal/") it would work.
What's the best solution for this problem?
Quick and dirty:
<script type="text/javascript">
var BASE_URL = '#Constants.BaseUrl';
</script>
where Constants is a static class defined as:
public static class Constants {
#if DEBUG
public const string BaseUrl = "/";
#else
public const string BaseUrl = "/bamportal/";
#endif
}
So when you compile your application in debug configuration you will get /, while in release you will get /bamportal/.
As alternative, a more complex and versatile approach could be obtained using Configuration Transforms and appSettings from Web.config:
<script type="text/javascript">
var BASE_URL = '#System.Configuration.ConfigurationManager.AppSettings["BaseUrl"];';
</script>
This, of course, will be extremely useful in scenarios where you need to deploy front-end and back-end on different domains/urls.
Your code should never know where the site will be hosted, you should use the correct helpers to determine where the action/content is located, this will prevent any issues with paths. Use Url.Content and Url.Action they will generate the correct path/url in the code.
As an example your action needs to point to the "MyTasks", "GetDataPage"
In your razor code you should have something like
<div id="urls" data-url="#Url.Action("ActionMethodName","YourControllerName")"></div>
Then in your get code get that stored url
$.getJSON($("#urls").data("url"),
To elaborate further this code will work on any environment (production, debug, iis, any location) without any developer worry or tweaking with config files or any other process. Tomorrow if you need to host your site on "osportal" not "bamportal" no changes need to be made, this should not be part of your code base.
One of the biggest benefits is that if the controller or action ever change the compiler will let you know that the url does not exist and you can fix it. Hardcoding paths/urls/location is a very bad/unmaintainable practice.

Angular 2 - How to have different values of a var/const for different environments?

I am developing a Angular 2/Ionic 2 + JEE 7 project and I have a very specific scenario:
I have a httpClient layer that encapsulates every call to backend, there is a const named REST_BASE_PATHthat I would like to point to my localhost when in development environment and to a specific address when in production.
That said I would like to know what is the best and most automatic way of accomplish that..
You could define a custom request options to centralize this:
export class AppRequestOptions extends BaseRequestOptions {
constructor(private #Inject('webApiBaseUrl') webApiBaseUrl:string) {
}
merge(options?:RequestOptionsArgs):RequestOptions {
options.url = this.webApiBaseUrl + options.url;
return super.merge(options);
}
}
The webApiBaseUrl value you inject could be defined when bootstrapping your application:
bootstrap(AppComponent, [
HTTP_PROVIDERS,
provide('webApiBaseUrl', { useValue: 'https://bookapi.apispark.net/v1' })
]);
Set base url for angular 2 http requests
You need to update the variable when package your application with the value for the production environment.
Here is a question regarding packaging that could help you at this level:
How do I actually deploy an Angular 2 + Typescript + systemjs app?

Resources