Optimizing Imports, Caching, and Metadata for SEO in Your Next.js Blog

Enhance your Next.js blog's performance with optimized imports, module aliases, caching for key functions, and dynamic metadata generation for better SEO.

Make Your Next.js Blog Faster and Smarter: Optimizing Imports, Caching, and Metadata for SEO

Hello, fellow developers! In our latest update to the Next.js blog, we've packed in some fantastic tweaks to make it zip along faster, stay organized, and shine in search results. We're talking refactoring imports, adding module aliases, boosting caching for our key functions, and dynamically generating metadata. Intrigued? Let's dive in!

Refactor Imports to Use Module Aliases

Ever felt like you're swimming in a sea of long import paths? We've been there! To tidy things up, we've switched to using module aliases. For example, instead of a long import like this:

-import { Config } from '../../../../utils/config';
+import { Config } from '@utils/config';

See the difference? Cleaner and much easier to manage!

You just have to update your tsconfig.json/tsconfig.base.json file to include the following configuration:

"baseUrl": "src",
"paths": {
  "@utils/config": ["utils/config/src/index.ts"]
}

Speed Up with Caching for Key Functions

Caching is like giving your website a shot of espresso—quick and efficient! We introduced caching to our frequently used functions, getArticleSlugs and getArticleBySlug, because both of them access files, in the case of getArticleBySlug it's used to build the article page itself, and separately to get the metadata per article, but it's the same data, why waste time fetching it twice? Here's how:

Cached getArticleSlugs Function

-const getArticleSlugs = async () => {
+const getArticleSlugs = cache(async () => {
  const articlesDirectory = path.join(process.cwd(), 'src/articles');
  const files = fs.readdirSync(articlesDirectory);
  const articles = files.map((filename) => {
    const slug = filename.replace(/.mdx$/, '');
    return { slug };
  });
  return articles;
});

Cached getArticleBySlug Function

-const getArticleBySlug = async (slug: string) => {
+const getArticleBySlug = cache(async (slug: string) => {
  const articlesDirectory = path.join(process.cwd(), 'src/articles');
  const filePath = path.join(articlesDirectory, `${slug}.mdx`);
  const markdownWithMetadata = fs.readFileSync(filePath, 'utf-8');
  const { data: frontMatter, content } = matter(markdownWithMetadata);
  const article = {
    frontMatter,
    content,
  };
  return article;
});

You just have to import { cache } from 'react';

Generate Metadata for Article Pages

We introduced a generateMetadata function to dynamically set the metadata for each article page based on its content. This helps in improving SEO and user experience.

export const generateMetadata = async ({ params }: { params: { slug: string } }): Promise<Metadata> => {
  const { frontMatter } = await getArticleBySlug(params.slug);
  return {
    title: frontMatter.title,
    description: frontMatter.description,
  };
};

Enhanced TypeScript Configuration

To keep our codebase robust and error-free, we bumped up our TypeScript settings with strictNullChecks and a few other goodies.

"compilerOptions": {
  "strict": true,
+  "strictNullChecks": true,
  "forceConsistentCasingInFileNames": true,
  // Other configurations
},

ESLint Configuration for Utils/Config

We gave utils/config its own little ESLint playground to maintain code quality and standards.

{
  "extends": ["../../.eslintrc.json"],
  "ignorePatterns": ["!**/*"],
  "overrides": [
    {
      "files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
      "rules": {}
    }
  ]
}

Conclusion

These changes significantly improve the performance, maintainability, and SEO of our Next.js blog. Refactoring imports to use module aliases, caching frequently used functions, and generating dynamic metadata are all steps toward a better-organized, faster, and more SEO-friendly application. Stay tuned for more updates!

Wrap Up

And there you have it! By refactoring imports to use module aliases, caching key functions, and generating dynamic metadata, we're looking at a faster, better-organized, and SEO-friendly Next.js blog. Stay tuned for more exciting updates!

← Back to posts

We use cookies to improve your experience and analyze our traffic. By using our site, you consent to our use of cookies. You can manage your preferences below: