I would probably do something like that.
const pathArr = pathname.split('/')
let nonExistentFolders
for (let i = 0; i < pathArr.length; i++) {
if (pathArr.match(/\d+/) && i+1 < pathArr.length) {
const folderName = pathArr[i+1]
// validate id and folder name
continue
}
nonExistentFolders = pathArr.slice(i, -1)
break
}
for (const folder of nonExistentFolders) {
// generate id/folder name pairs
}
// push new route
Have you thought of using next.js' property params
in the page's component?
It could first of all simplify the pathname logic.