Best way to manage URL case sensitivity

  • 17 August 2022
  • 3 replies
  • 79 views

Userlevel 1
Badge

Best way to manage URL case sensitivity? 

 

We are building a site where we want all URLs to be case insensitive. On the code side, we are using NextJS with middleware which redirects all router requests to a lowercase URL

import { NextResponse } from 'next/server';

const Middleware = (req) => {
if (req.nextUrl.pathname === req.nextUrl.pathname.toLowerCase()) return NextResponse.next();

return NextResponse.redirect(new URL(req.nextUrl.origin + req.nextUrl.pathname.toLowerCase()));
};

export default Middleware;

Using the JavaScript SDK, we are getting Entries from ContentStack with a URL query

  getEntryByUrl(contentTypeUid, entryUrl, referenceFieldPath) {
return new Promise((resolve, reject) => {
const query = Stack.ContentType(contentTypeUid).Query();
if (referenceFieldPath) query.includeReference(referenceFieldPath);
const data = query.where('url', `${entryUrl}`).toJSON().find();
data.then(
(result) => {
resolve(result[0]);
},
(error) => {
reject(error);
}
);
});
},

The problem is that in ContentStack, it doesn’t seem like there is an option to enforce case inputs on the URL input field, and the query method in the SDK seems to be case sensitive. This means that the page will 404 if a content entry has capital letters in the URL. This current pattern also seems to allow for duplicate URL entries even if you set {"enforce_unique_urls": true} in the CMA if one entry has a capitalized URL and one is lowercase (ie “/About” vs “/about”)

 

What would be the best way to manage URL case if you want all entries to follow the same pattern (ie camelcase, lowercase etc)? Is there a way to make the Stack.query method case insensitive, or set case rules on the URL input field?

 

Thanks!

 

 

 


3 replies

Userlevel 2

Hi @will , currently we do not have the provision to enforce the case sensitive behaviour on our inbuilt URL field. However we would suggest you to achieve your use case using a single Line Textbox and applying a regex pattern on that to accept the values in lower case along with the unique property available in our UI. This would restrict entering uppercase and duplicate URL values.

You can also create a custom URL field using our extensions feature which will help you to allow only unique lowercase values.

However, in order to achieve your use case for an existing URL field, please try the below query and let us know if it helps

query.regex('url', `^${entryUrl}`, 'i').toJSON().find();

https://www.contentstack.com/docs/developers/apis/content-delivery-api/#equals-operator:~:text=in%20order%20[…]%20a%20case%2Dinsensitive%20search%2C

Userlevel 1
Badge

Thanks @Sachin! Having the middleware and the case insensitive regex query solves this problem for us

Userlevel 2

Awesome! Glad to hear that @will .

Reply