Angular Universal app not honoring 'useAbsoluteUrl' or HTTP Interceptor on server-side - node.js

Our Angular 14 app is configured to use Angular Universal for SSR, and is integrated with our .NET 6 back end. The Universal guide incorrectly states (per this bug) that relative URLs will "automatically" be converted to absolute if you're using Express, but we still get relative URL errors from SSR even after updating our app.server.module.ts to include the necessary setting .useAbsoluteUrl = true (and providing the base URL), which fixes the issue for some per the bug thread:
export class AppServerModule {
constructor(
#Inject(INITIAL_CONFIG) private config: PlatformConfig,
private baseUrlService: BaseUrlService
) {
this.config.baseUrl = this.baseUrlService.getBaseUrl();
this.config.useAbsoluteUrl = true;
}
}
We've also tried implementing a custom HTTP Interceptor to handle the conversion, which doesn't seem to work either when declared as a provider in app.server.module.ts. This must be a misconfiguration issue, right? Our main.server.ts file imports the aspnet-prerendering package and has a default createServerRenderer() method, which calls renderModule(AppServerModule, options), but is something else missing with this approach? The main.server.ts is:
....
export default createServerRenderer(params => {
const { AppServerModule } = (module as any).exports;
const options = {
document: params.data.originalHtml,
url: params.url,
extraProviders: [
{ provide: APP_BASE_HREF, useValue: params.baseUrl },
{ provide: 'BASE_URL', useValue: params.origin }
]
};
// Bypass ssr api call cert warnings in development
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
const renderPromise = renderModule(AppServerModule, options);
return renderPromise.then(html => ({ html }));
});
export { renderModule } from '#angular/platform-server';
export { AppServerModule } from './app/app.server.module';
Microsoft's now-deprecated NodeServices implementation(?) apparently requires the use of commonjs for Node (in tsconfig.server.json), if that's relevant.

Related

How does one secure api keys on sveltekit 1.0

I am using ghost, i made an integration and i would like to hide the api key from the front-end. I do not believe i can set restrictions on the ghost cms (that would also work). And i do believe so +page.js files are run on the browser also, so im a little confused on how to achieve this?
The interal sveltekit module $env/static/private (docs) is how you use secure API keys. Sveltekit will not allow you to import this module into client code so it provides an extra layer of safety. Vite automatically loads your enviroment variables from .env files and process.env on build and injects your key into your server side bundle.
import { API_KEY } from '$env/static/private';
// Use your secret
Sveltekit has 4 modules for accessing enviroment variables
$env/static/private (covered)
$env/static/public accessiable by server and client and injected at build (docs)
$env/dynamic/private provided by your runtime adapter; only includes variables with that do not start with the your public prefix which defaults to PUBLIC_ and can only be imported by server files (docs)
$env/dynamic/public provided by your runtime adapter; only includes variables with that do start with the your public prefix which defaults to PUBLIC_ (docs)
You don't need to hide the key.
Ghost Content API Docs:
These keys are safe for use in browsers and other insecure environments, as they only ever provide access to public data.
One common way to hide your third-party API key(s) from public view is to set up proxy API routes.
The general idea is to have your client (browser) query a proxy API route that you provide/host, have that proxy route query the third-party API using your credentials (API key), and pass on the results from the third-party API back to the client.
Because the query to the third-party API takes place exclusively on the back-end, your credentials are never exposed to the client (browser) and thus not visible to the public.
In your use case, you would have to create 3 dynamic endpoint routes to replicate the structure of Ghost's API:
src/routes/api/[resource]/+server.js to match /posts/, /authors/, /tags/, etc.:
const API_KEY = <your_api_key>; // preferably pulled from ENV
const GHOST_URL = `https://<your_ghost_admin_domain>/ghost/api/content`;
export function GET({ params, url }) {
const { resource } = params;
const queryString = url.searchParams.toString();
return fetch(`${GHOST_URL}/${resource}/?key=${API_KEY}${queryString ? `&${queryString}` : ''}`, {
headers: {
'Accept-Version': '5.0' // Ghost API Version setting
}
});
}
src/routes/api/[resource]/[id]/+server.js to match /posts/{id}/, /authors/{id}/, etc.:
const API_KEY = <your_api_key>; // preferably pulled from ENV
const GHOST_URL = `https://<your_ghost_admin_domain>/ghost/api/content`;
export function GET({ params, url }) {
const { resource, id } = params;
const queryString = url.searchParams.toString();
return fetch(`${GHOST_URL}/${resource}/${id}/?key=${API_KEY}${queryString ? `&${queryString}` : ''}`, {
headers: {
'Accept-Version': '5.0' // Ghost API Version setting
}
});
}
src/routes/api/[resource]/slug/[slug]/+server.js to match /posts/slug/{slug}/, /authors/slug/{slug}/, etc.:
const API_KEY = <your_api_key>; // preferably pulled from ENV
const GHOST_URL = `https://<your_ghost_admin_domain>/ghost/api/content`;
export function GET({ params, url }) {
const { resource, slug } = params;
const queryString = url.searchParams.toString();
return fetch(`${GHOST_URL}/${resource}/slug/${slug}/?key=${API_KEY}${queryString ? `&${queryString}` : ''}`, {
headers: {
'Accept-Version': '5.0' // Ghost API Version setting
}
});
}
Then all you have to do is call your proxy routes in place of your original third-party API routes in your app:
// very barebones example
<script>
let uri;
let data;
async function get() {
const res = await fetch(`/api/${uri}`);
data = await res.json();
}
</script>
<input name="uri" bind:value={uri} />
<button on:click={get}>GET</button>
{data}
Note that using proxy API routes will also have the additional benefit of sidestepping potential CORS issues.

How to reference the app instance in a module in Nest.js

I'm working on a project that's using multiple Nest repos, around 4.
Every repo needs to implementing logging to log things like
Server lifecycle events
Uncaught errors
HTTP requests/responses
Ideally, I'd like to package everything up into a module which I can publish to my company's NPM organization and just consume directly in each of my projects.
That way, it would take very minimal code to get logging set up in each project.
One of the things I'd like to log in my server lifecycle event is the server's url.
I know you can get this via app.getUrl() in the bootstrapping phase, but it would be great to have access to the app instance in a module's lifecycle hook like so.
#Module({})
export class LoggingModule implements NestModule {
onApplicationBootstrap() {
console.log(`Server started on ${app.getUrl()}`)
}
beforeApplicationShutdown() {
console.log('shutting down')
}
onApplicationShutdown() {
console.log('successfully shut down')
}
configure(consumer: MiddlewareConsumer) {
consumer.apply(LoggingMiddleware).forRoutes('*')
}
}
Is this possible?
There's no way (besides hacky ones, maybe) to access the app itself inside modules.
As you can see here, app.getUrl() uses the underlying HTTP server. Thus I guess you can retrieve the same data using the provider HttpAdapterHost.
Ï thought I'd chime in and offer one of the hacky solutions. Only use this, if there is absolutely no other way or your deadline is coming in an hour.
Create a class that can hold the application instance
export class AppHost {
app: INesApplication
}
And a module to host it
#Module({
providers: [AppHost]
exports: [AppHost]
})
export class AppHostModule {}
In your bootstrap() function, retrieve the AppHost instance and assign the app itself
// after NestFactory.create() ...
app.select(AppHostModule).get(AppHost).app = app;
Now, the actual application will be available wherever you inject AppHost.
Be aware, though, that the app will not be available inside AppHost before the whole application bootstraps (in onModuleInit, onApplicationBootstrap hooks or in provider factories), but it should be available in shutdown hooks.
Not sure is that hacky... I'm using this to prevent the server from starting in case of pending migrations.
// AppModule.ts
export class AppModule implements NestModule {
app: INestApplication;
async configure(consumer: MiddlewareConsumer) {
if (await this.hasPendingMigrations()) {
setTimeout(()=> {
this.logger.error("There are pending migrations!")
process.exitCode = 1;
this.app.close();
}, 1000);
}
//...
}
public setApp(app: INestApplication) {
this.app = app;
}
//...
}
//main.ts
const app = await NestFactory.create(AppModule, {
logger: config.cfgServer.logger,
});
app.get(AppModule).setApp(app);

Cannot set property 'userId' of undefined in session variable

Cannot read set property of 'userId' of undefined is a classic error that has been experienced in Express frameworks and documentation here covers what to do about it, but how do you resolve this issue in a NestJS application?
When you get an error message that says Cannot set property 'userId' of undefined you want to look at what is going on with your cookie-session.
Do you have a cookie-session installed?
The error is being thrown whenever you try to set the user id property on the users' session object, because that cookie middleware is not installed or it's not running, you get undefined.
So when you try to set a property on undefined, you get this classic error message.
So your cookie-session may not be set up.
Enough answers were given in a plain ExpressJS API, but what if you are working with NestJS? Well, here is the NestJS way to resolve this.
Import the following to your app.module.ts file:
import { Module, ValidationPipe } from '#nestjs/common';
import { APP_PIPE } from '#nestjs/core';
Go down to your list of providers and inside the array and a brand new object:
providers: [
AppService,
{
provide: APP_PIPE,
useValue: new ValidationPipe({
whitelist: true,
}),
},
],
So what does this really do? It says whenever we create an instance of the app module, automatically make use of it. Apply it to every incoming request that flows to the application, run it through the instance of a class. That's how to set up a global pipe, but you have to set up the cookie session middleware into a global middleware.
You need to import the following to the same file:
import { MiddlewareConsumer, Module, ValidationPipe } from '#nestjs/common';
At the bottom, add the following:
export class AppModule {
configure(consumer: MiddlewareConsumer) {}
}
The configure function gets called automatically whenever the application starts listening for incoming traffic. So inside of here I can set up some middleware that will run on every single incoming request.
To do, we call or reference consumer.apply() like so:
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(
cookieSession({
keys: ['dfghjkl'],
}),
);
}
}
I then need to ensure I add in a require statement for cookie session at the top:
const cookieSession = require('cookie-session');
And at the bottom also add:
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(
cookieSession({
keys: ['dfghjkl'],
}),
)
.forRoutes('*');
}
}
That means that I want to make use of the middleware on every single incoming request that comes into the application. That should be it.

Unable to add an UI extension on Contentful. When i run nopm run start, I get a 404 error on ui_config

I am new to contentful. I am trying to develop an UI extension on Contentful using Contentful SDK.
I followed all the steps mentioned in this article.
This is the code I have in index.js.
import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import { TextInput , Button } from '#contentful/forma-36-react-components';
import { init } from 'contentful-ui-extensions-sdk';
import '#contentful/forma-36-react-components/dist/styles.css';
import './index.css';
export class App extends React.Component {
static propTypes = {
sdk: PropTypes.object.isRequired
};
detachExternalChangeHandler = null;
constructor(props) {
super(props);
this.state = {
value: props.sdk.field.getValue() || ''
};
}
componentDidMount() {
this.props.sdk.window.startAutoResizer();
// Handler for external field value changes (e.g. when multiple authors are working on the same entry).
this.detachExternalChangeHandler = this.props.sdk.field.onValueChanged(this.onExternalChange);
}
componentWillUnmount() {
if (this.detachExternalChangeHandler) {
this.detachExternalChangeHandler();
}
}
onExternalChange = value => {
this.setState({ value });
};
onChange = e => {
const value = e.currentTarget.value;
this.setState({ value });
if (value) {
this.props.sdk.field.setValue(value);
} else {
this.props.sdk.field.removeValue();
}
};
onButtonClick = async () => {
console.log('hurray');
};
render() {
return (
<Button buttonType="primary" isFullWidth={false}
onClick={this.onButtonClick}>
Add Content from AEM DAM
</Button>
);
}
}
Ideally i am trying to create an UI extension to be used in contentful space. I downloaded the contentful SDK and i have put in a button. But I receive this error on the console and it doesn't work
Screenshot:
https://github.com/contentful/create-contentful-extension
Go to the content of this Content Type and enable mixed content at
your browser so that development version that is served from your
local machine could be rendered within https://app.contentful.com.
Better yet:
I'm not the biggest fan of disabling the mixed content setting in browsers. Can I use HTTPS in development mode?
Yes, you can serve your extension using HTTPS. Add --https to start command.
"start": "contentful-extension-scripts start --https",
It uses Parcel HTTPS under the hood , which generates a self-signed certificate, you might have to configure your browser to allow self-signed certificates for localhost.
I think that will fix the 404 error and get things working.
Please follow the readme carefully and post a separate question if you still have problems.

NodeJS + RxDB + Electron w/ persistent data

I have been playing around with PouchDB (using express-pouchdb and pouchdb-find) for a while and realized that I needed to work with some streams through Rxjs for my Angular 5/Electron app.
For my current setup, I run express-pouchdb to set up a localized PouchDB for persistence and then in Angular I have the following:
#Injectable()
export class PouchdbService {
private _localdb = 'http://localhost:3000/main';
private _pouchDb: any;
constructor() {
this._pouchDb = new PouchDB(this._localdb);
PouchDB.plugin(PouchDBFind);
this.createIndexes();
}
private createIndexes(): void {
this._pouchDb.createIndex({
index: {
fields: [ 'tags' ]
}
});
this._pouchDb.createIndex({
index: {
fields: [ 'date' ]
}
})
this._pouchDb.createIndex({
index: {
fields: [ 'title' ]
}
});
}
This provides my service to the express app through _localdb property. I could keep the PouchDB express app and just call it through RxDB by rewriting my service and refactoring the code. However, I guess that I need have to call sync on every collection.
Though, I would rather drop the express application if there was a way to run with persistence with RxDB directly.
I ended up using the websql adapter which apparently stores information between application loads and dropped express-pouchdb.

Resources