Need slugify functionality for Notion API pages in Next.js. 404 error occurs when swapping IDs with titles. How can I create proper slugs? See sample:
import { createClient } from '@notionhq/client';
const client = createClient({ auth: process.env.API_SECRET });
export const fetchRecords = async (dbIdentifier) => {
const result = await client.databases.query({ database_id: dbIdentifier });
return result.results;
};
export const fetchEntry = async (entryId) => {
return await client.pages.retrieve({ page_id: entryId });
};
export const makeSlug = (text) => text.toLowerCase().trim().replace(/\s+/g, '-');
hey, maybe u need to strip out non alphanum chracters too. i switched from plain regex to a slugify npm module and that fixed the 404s for me. try it out
I solved this issue by taking a twofold approach: refining my custom regex and implementing additional checks for edge cases that standard slugify functions sometimes miss. I found that simply lower-casing and replacing spaces was insufficient when specific Unicode characters and punctuation were introduced through the API. By extending my filtering to remove characters that might interfere with URL routing, I managed to avoid the 404 errors. In some cases, a hybrid method combining regex adjustments with a fallback to a library function, if necessary, provided an extra layer of stability.
In my experience, a more robust solution is to enhance the sanitization of your slug. I encountered similar issues when certain special characters slipped through a basic regex. What worked for me was carefully filtering out not just spaces but also any characters that might disrupt the URL structure. I modified my regex to permit only letters, numbers, and a few selected symbols. This approach not only improved the SEO aspect but also prevented unexpected 404 errors. Alternatively, using a tested library for slug generation could also be beneficial if you want to simplify your maintenance.