Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Store and fetch common application data in Next.js

While working on one of my applications called LinkSnatch, I needed to store some common application data in a central place so that I can access it from anywhere in the application and I don’t have to hardcode those details.

And since the application is built using Next.js, it’s pretty easy to do so. Here’s how I have implemented it.

Essentially, when you create a Next.js application, it comes with its own configuration file called next.config.js which is used to configure the application. And in this file, you can add custom configuration to the application.

We can add publicRuntimeConfig to the next.config.js file to store some common application data. Here’s how I have done it.

const nextConfig = {
  publicRuntimeConfig: {
    app_name: 'LinkSnatch',
    app_short_description: 'Dead simple bookmarks',
    description: 'An effortlessly simple bookmarks app on the go.',
    app_url: 'https://linksnatch.pages.dev',
    app_creator: '@amit_merchant',
    app_locale: 'en_US',
    app_theme_color: '#CABCFD',
    jsonlink_api_url: 'https://jsonlink.io/api',
  },
}

As you can tell, I have added publicRuntimeConfig to the next.config.js file and then added some common application data to it.

Now, we can access this data from anywhere in the application like so.

import { publicRuntimeConfig } from 'next.config'

export default function Home() {
    return (
        <div>
            <h1>{publicRuntimeConfig.app_name}</h1>
            <p>{publicRuntimeConfig.app_short_description}</p>
        </div>
    )
}

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?