Replaced SSR with custom script to prerender metadata for crawlers

This commit is contained in:
itzMiney committed 2024-12-30 14:08:44 +01:00
1 parent 5091aadcea
commit 26bf465a57
10 files changed
+219 -162

No files matched your search

+24 -25
View File
@@ -13,7 +13,6 @@
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"aot": true,
"outputPath": "dist/itzmineydev",
"index": "src/index.html",
"browser": "src/main.ts",
@@ -28,27 +27,35 @@
}
],
"styles": [
"@angular/material/prebuilt-themes/magenta-violet.css",
"src/styles.css"
],
"scripts": []
"scripts": [
]
},
"configurations": {
"csr": {
"browser": "src/main.ts",
"aot": true
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kB",
"maximumError": "1MB"
},
"ssr": {
"browser": "src/main.ts",
"server": "src/main.server.ts",
"outputMode": "server",
"ssr": {
"entry": "src/server.ts"
{
"type": "anyComponentStyle",
"maximumWarning": "4kB",
"maximumError": "8kB"
}
],
"outputHashing": "all"
},
"aot": true
}
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
@@ -57,15 +64,9 @@
},
"development": {
"buildTarget": "itzmineydev:build:development"
},
"csr": {
"buildTarget": "itzmineydev:build:csr"
},
"ssr": {
"buildTarget": "itzmineydev:build:ssr"
}
},
"defaultConfiguration": "csr"
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n"
@@ -82,11 +83,9 @@
{
"glob": "**/*",
"input": "public"
},
"src/assets"
}
],
"styles": [
"@angular/material/prebuilt-themes/magenta-violet.css",
"src/styles.css"
],
"scripts": []
@@ -96,6 +95,6 @@
}
},
"cli": {
"analytics": "7c748d65-f240-495f-a7b6-3433648bdabf"
"analytics": "d1479826-daae-48a2-af4d-c698a5b01a13"
}
}
+59 -1
View File
@@ -22,6 +22,7 @@
"@angular/ssr": "^19.0.6",
"@fortawesome/fontawesome-free": "^6.7.2",
"@types/three": "^0.171.0",
"axios": "^1.7.9",
"express": "^4.18.2",
"ngx-device-detector": "^9.0.0",
"ngx-meta": "^0.0.1",
@@ -5821,6 +5822,12 @@
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==",
"license": "MIT"
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
"license": "MIT"
},
"node_modules/autoprefixer": {
"version": "10.4.20",
"resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.20.tgz",
@@ -5859,6 +5866,17 @@
"postcss": "^8.1.0"
}
},
"node_modules/axios": {
"version": "1.7.9",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.7.9.tgz",
"integrity": "sha512-LhLcE7Hbiryz8oMDdDptSrWowmB4Bl6RCt6sIJKpRB4XtVf0iEgewX3au/pJqm+Py1kCASkb/FFKjxQaLtxJvw==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",
"proxy-from-env": "^1.1.0"
}
},
"node_modules/babel-loader": {
"version": "9.2.1",
"resolved": "https://registry.npmjs.org/babel-loader/-/babel-loader-9.2.1.tgz",
@@ -6635,6 +6653,18 @@
"dev": true,
"license": "MIT"
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"license": "MIT",
"dependencies": {
"delayed-stream": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/commander": {
"version": "2.20.3",
"resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
@@ -7103,6 +7133,15 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
"license": "MIT",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
@@ -7985,7 +8024,6 @@
"version": "1.15.9",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
"integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==",
"dev": true,
"funding": [
{
"type": "individual",
@@ -8019,6 +8057,20 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/form-data": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.1.tgz",
"integrity": "sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==",
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/forwarded": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
@@ -11795,6 +11847,12 @@
"node": ">= 0.10"
}
},
"node_modules/proxy-from-env": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
"license": "MIT"
},
"node_modules/prr": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz",
+1
View File
@@ -25,6 +25,7 @@
"@angular/ssr": "^19.0.6",
"@fortawesome/fontawesome-free": "^6.7.2",
"@types/three": "^0.171.0",
"axios": "^1.7.9",
"express": "^4.18.2",
"ngx-device-detector": "^9.0.0",
"ngx-meta": "^0.0.1",
+133
View File
@@ -0,0 +1,133 @@
const fs = require('fs');
const path = require('path');
const axios = require('axios');
// Define metadata for routes
const staticMeta = {
'/': {
title: 'itzMiney\'s Home',
description: 'Welcome to itzMiney\'s Homepage! Here you can find my portfolio and other cool stuff.',
image: 'https://meta.itzminey.dev/assets/ogimg.png',
url: 'https://itzminey.dev/about',
color: '#eb284c'
},
'/about': {
title: 'itzMiney\'s Home',
description: 'Welcome to itzMiney\'s Homepage! Here you can find my portfolio and other cool stuff.',
image: 'https://meta.itzminey.dev/assets/ogimg.png',
url: 'https://itzminey.dev/about',
color: '#eb284c'
},
'/portfolio': {
title: 'Portfolio | itzMiney',
description: 'This is my portfolio where you can find examples of my designs and other projects!',
image: 'https://meta.itzminey.dev/assets/ogimg.png',
url: 'https://itzminey.dev/portfolio',
color: '#eb284c'
},
'/blog': {
title: 'Blog | itzMiney',
description: 'Welcome to my blog! I\'ll post occasional updates here on the stuff I\'m currently up to.',
image: 'https://meta.itzminey.dev/assets/ogimg.png',
url: 'https://itzminey.dev/blog',
color: '#eb284c'
},
'/login': {
title: 'Login | itzMiney',
description: 'Admin Panel Login',
image: 'https://meta.itzminey.dev/assets/ogimg.png',
url: 'https://itzminey.dev/login',
color: '#eb284c'
},
'/admin': {
title: 'Admin Panel | itzMiney',
description: 'Admin Panel',
image: 'https://meta.itzminey.dev/assets/ogimg.png',
url: 'https://itzminey.dev/admin',
color: '#eb284c'
},
'/404': {
title: '404 | Page Not Found',
description: 'How the hell did you end up here?',
image: 'https://meta.itzminey.dev/assets/ogimg.png',
url: 'https://itzminey.dev/404',
color: '#eb284c',
},
};
// Output directory for pre-rendered metadata
const outputDir = path.join(__dirname, '../dist/itzmineydev/meta');
// Ensure the output directory exists
fs.mkdirSync(outputDir, { recursive: true });
// Function to fetch dynamic metadata
async function fetchDynamicMeta() {
try {
const response = await axios.get('https://itzminey.dev/api/articles'); // Replace with your API endpoint
const articles = response.data;
return articles.reduce((acc, article) => {
const updatedAt = new Date(article.updatedAt);
const formattedUpdatedAt = updatedAt.toLocaleDateString('de-DE', {
hour: '2-digit',
minute: '2-digit',
day: '2-digit',
month: '2-digit',
year: 'numeric',
});
const description = `By ${article.authorName} | Views: ${article.views} | Last Updated: ${formattedUpdatedAt}`;
acc[`/blog/${article.slug}`] = {
title: article.title,
description: description,
image: 'https://meta.itzminey.dev/assets/ogimg.png',
url: `https://itzminey.dev/blog/${article.slug}`,
color: '#eb284c',
};
return acc;
}, {});
} catch (error) {
console.error('Error fetching dynamic metadata:', error);
return {};
}
}
function ensureFolderExists(folderPath) {
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath, { recursive: true });
}
}
// Function to generate metadata files
async function generateMetaFiles() {
const dynamicMeta = await fetchDynamicMeta();
const allMeta = { ...staticMeta, ...dynamicMeta };
Object.entries(allMeta).forEach(([route, meta]) => {
const routePath = route === '/' ? 'index.html' : 'index.html';
const folderPath = path.join(outputDir, route === '/' ? '' : route.replace(/\//g, '/'));
const filePath = path.join(folderPath, routePath);
// Ensure the folder path exists
ensureFolderExists(folderPath);
// Generate metadata content
const metaTags = `
<title>${meta.title}</title>
<meta name="description" content="${meta.description}">
<meta property="og:title" content="${meta.title}">
<meta property="og:description" content="${meta.description}">
<meta property="og:image" content="${meta.image}">
<meta property="og:url" content="${meta.url}">
<meta name="theme-color" content="${meta.color}">
`;
// Write the metadata to the file
fs.writeFileSync(filePath, metaTags.trim());
console.log(`Generated metadata for ${route}: ${filePath}`);
});
}
generateMetaFiles().then();
console.log('Metadata generation complete!')
-14
View File
@@ -1,14 +0,0 @@
import {ApplicationConfig, mergeApplicationConfig} from '@angular/core';
import {provideServerRendering} from '@angular/platform-server';
import {provideServerRoutesConfig} from '@angular/ssr';
import {appConfig} from './app.config';
import {serverRoutes} from './app.routes.server';
const serverConfig: ApplicationConfig = {
providers: [
provideServerRendering(),
provideServerRoutesConfig(serverRoutes)
]
};
export const config = mergeApplicationConfig(appConfig, serverConfig);
-36
View File
@@ -1,36 +0,0 @@
import {RenderMode, ServerRoute} from '@angular/ssr';
export const serverRoutes: ServerRoute[] = [
{
path: '',
renderMode: RenderMode.Prerender,
},
{
path: 'about',
renderMode: RenderMode.Client,
},
{
path: 'portfolio',
renderMode: RenderMode.Prerender,
},
{
path: 'blog',
renderMode: RenderMode.Prerender,
},
{
path: 'blog/:slug',
renderMode: RenderMode.Client,
},
{
path: 'admin',
renderMode: RenderMode.Client,
},
{
path: 'login',
renderMode: RenderMode.Client,
},
{
path: '**',
renderMode: RenderMode.Client,
}
]
-7
View File
@@ -1,7 +0,0 @@
import {bootstrapApplication} from '@angular/platform-browser';
import {AppComponent} from './app/app.component';
import {config} from './app/app.config.server';
const bootstrap = () => bootstrapApplication(AppComponent, config);
export default bootstrap;
-58
View File
@@ -1,58 +0,0 @@
import {AngularNodeAppEngine, createNodeRequestHandler, isMainModule,} from '@angular/ssr/node';
import express from 'express';
import {dirname, resolve} from 'node:path';
import {fileURLToPath} from 'node:url';
const serverDistFolder = dirname(fileURLToPath(import.meta.url));
const browserDistFolder = resolve(serverDistFolder, '../browser');
const app = express();
const angularApp = new AngularNodeAppEngine();
/**
* Example Express Rest API endpoints can be defined here.
* Uncomment and define endpoints as necessary.
*
* Example:
* ```ts
* app.get('/api/**', (req, res) => {
* // Handle API request
* });
* ```
*/
/**
* Serve static files from /browser
*/
app.use(
express.static(browserDistFolder, {
maxAge: '1y',
index: false,
redirect: false,
}),
);
/**
* Handle all other requests by rendering the Angular application.
*/
app.use('/**', (req, res, next) => {
angularApp.handle(req)
.then(response => response ? res.send(response) : next())
.catch(next);
});
/**
* Start the server if this module is the main entry point.
* The server listens on the port defined by the `PORT` environment variable, or defaults to 4000.
*/
if (isMainModule(import.meta.url)) {
const port = process.env['PORT'] || 4000;
app.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
/**
* The request handler used by the Angular CLI (dev-server and during build).
*/
export const reqHandler = createNodeRequestHandler(app);
+2 -6
View File
@@ -4,14 +4,10 @@
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": [
"node"
]
"types": []
},
"files": [
"src/main.ts",
"src/main.server.ts",
"src/server.ts"
"src/main.ts"
],
"include": [
"src/**/*.d.ts"
-15
View File
@@ -1,15 +0,0 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
},
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}