Responsive Advertisement

Dynamic/Pretty URL in Experience Cloud Sites

 You made a fantastic looking site following Salesforce design patterns and custom styles. But your URLs look ugly (like /custom-account?accountNumber=230456&event=dealclose). You have a custom page for your UI and you made it dynamic (dynamic content) by using URL parameters. Unfortunately, Salesforce Experience Cloud site doesn't support dynamic URLs for custom pages, unlike the other front-end frameworks (almost every UI framework has dynamic urls like /post/[:id] or equivalent). These URLs are user friendly. The URL parameters are not user friendly (URL parameters often are encoded). In this blog post, we will see one way (a hack TBH) using which we will create pretty user friendly URLs for Experience Cloud sites.

NOTE: Salesforce Sites (Visualforce sites) support user friendly URL generation natively using UrlRewriter Interface in Apex. (ref: developer.salesforce.com)

The Solution/Hack

Okay, the idea came to me when I tried to open a page that does not exist (page not created in the site). It opened the Error page(default available with all sites). So I replaced the Error page content with a custom component, to read the window.location global variable. Now, from it, I extracted whatever there is in the URL after the site's base path. After that, it is easy, just run a switch statement in the render method and return what template you want to render. (This is, roughly, the same way how front-end routing works)
import { LightningElement } from 'lwc';
import basePath from '@salesforce/community/basePath';
import DEFAULT from './dynamicContent.html';
import ACCOUNT from './account.html';
import CONTACT from './contact.html';
export default class DynamicContent extends LightningElement {
get _pathname() {
const pathname = window.location.pathname;
// we are adding 1 to the basePath length, as basePath does not include '/' at the end
return pathname.substring(pathname.lastIndexOf(basePath) + basePath.length + 1);
}
get parts() {
return this._pathname.split('/');
}
get params() {
return this.parts.slice(0);
}
get pageName() {
return this.parts.at(0);
}
render() {
switch (this.pageName) {
case 'account':
return ACCOUNT;
case 'contact':
return CONTACT;
default:
return DEFAULT;
}
}
}
Important: Note that, you must open the url either with anchor tag or using lightning navigation with standard__webPage page reference type (does not work with comm_namedPage type). I could not make it to work on the new LWR site template (window.location has no readable properties for some reason). The example I tried was with BYO Aura template.
That's it for this post. Stay tuned for more, and keep hustling in your adventures in Salesforce.

Post a Comment

0 Comments