Yes, you can use non-English characters, such as Japanese, in your URL slugs with Next.js and Sanity.io. Here's how you can implement this:
1. Modify the Slug Field in Your Sanity Schema
By default, Sanity's slug field uses a slugify function to convert input text into a URL-friendly format, which usually strips out non-ASCII characters. To allow non-English characters in your slugs, you need to adjust this function.
Update your slug field definition to allow Unicode characters:
{
type: 'slug',
name: 'slug',
title: 'Slug',
options: {
source: 'title',
maxLength: 200,
// Modify the slugify function to allow non-English characters
slugify: (input) => input, // Keeps the original input, including Japanese characters
}
}
Explanation:
slugify Function: By setting slugify to an identity function (input) => input, you allow the slug field to accept and store the title as is, including any non-English characters.
source: This should point to the field from which the slug is generated, typically the title of your article.
2. Ensure Next.js Handles Non-English Slugs in Routes
Next.js supports dynamic routes with non-English characters. You need to ensure that your dynamic routes and data fetching methods correctly handle these slugs.
Define Dynamic Routes in pages/articles/[slug].js:
// pages/articles/[slug].js
import { useRouter } from 'next/router';
// Fetch data based on the slug
export async function getStaticProps({ params }) {
const { slug } = params;
// Fetch the post data using the slug
const post = await fetchPostBySlug(slug);
return {
props: { post },
};
}
// Define all possible slugs for static generation
export async function getStaticPaths() {
const posts = await fetchAllPosts();
const paths = posts.map((post) => ({
params: { slug: post.slug.current },
}));
return { paths, fallback: false };
}
const ArticlePage = ({ post }) => {
// Render your article page using the post data
};
export default ArticlePage;
Explanation:
getStaticProps: Receives the slug from the URL, which can include non-English characters, and fetches the corresponding post.
getStaticPaths: Generates the list of paths for static generation, including slugs with non-English characters.
3. Generate Links Correctly in Your Next.js Components
When linking to articles with non-English slugs, ensure the links are correctly encoded.
Example in a Component Rendering a List of Posts:
import Link from 'next/link';
const ArticlesList = ({ posts }) => (
<ul>
{posts.map((post) => (
<li key={post._id}>
<Link href={`/articles/${encodeURIComponent(post.slug.current)}`}>
{post.title}
</Link>
</li>
))}
</ul>
);
Explanation:
encodeURIComponent: Encodes the slug to ensure special characters are correctly represented in the URL.
Link Component: Next.js's Link component handles routing and ensures that links work correctly when clicked.
4. Test Your Implementation
After making these changes:
- Create a New Article with a Japanese Title: In Sanity Studio, create a new post with a title like "こんにちは" and ensure the slug field reflects this title.
- Build and Run Your Next.js App: Generate and serve your Next.js application to test the routing.
- Access the Article: Navigate to
www.example.com/articles/こんにちは and verify that the article loads correctly.
- Check Links and Navigation: Ensure that all links to the article are working and that navigation behaves as expected.
Considerations and Best Practices
- Browser Support: Modern browsers support Unicode in URLs and will handle non-English characters appropriately.
- URL Encoding: Always use
encodeURIComponent when constructing URLs programmatically to handle special characters.
- SEO Implications: Using non-English characters in URLs is generally acceptable, but be mindful that some older systems and crawlers might have issues. Always monitor your site's SEO performance if this is a concern.
- Consistent Slug Generation: If you have existing content with ASCII slugs, ensure that your site can handle both ASCII and non-ASCII slugs consistently.
Optional: Transliteration or Alternative Slugs
If you encounter issues or prefer to have ASCII-only URLs for compatibility reasons, you can implement a transliteration function to convert non-English titles into ASCII slugs.
Example Using a Transliteration Library:
const transliterate = require('transliteration');
{
type: 'slug',
name: 'slug',
title: 'Slug',
options: {
source: 'title',
maxLength: 200,
slugify: (input) => transliterate.slugify(input),
}
}
Explanation:
- Transliteration: Converts non-English characters into a phonetic equivalent using ASCII characters.
- Consistency: This approach provides URLs that are more universally compatible but may not reflect the original language accurately.
Summary
By adjusting your Sanity schema and ensuring your Next.js routes and links are correctly configured, you can use non-English characters in your URL slugs. This allows you to have URLs like www.example.com/articles/こんにちは and support content in Japanese or other languages seamlessly.
Remember to:
- Modify the slug field to accept non-English characters.
- Use
encodeURIComponent when generating URLs.
- Test thoroughly to ensure compatibility and correct behavior.
By following these steps, you'll be able to implement non-English slugs in your blog website successfully.