So far the path to the articles folder, where we host all of the markdown files, is hard-coded into our Next.js page component. In the long run, we wouldn't want to leave it like that. First of all to give greater flexibility in customizing the path if we ever decide to move it to another place, but also to make it more easily accessible by other parts of our Nx workspace libraries and apps.
This is a perfect use case for environment variables. In this lesson, we learn about how Nx, as well as Next.js, is able to read environment variables.
Prefer to read along as well? Here's the accompanying article.
Instructor: [0:00] Right now, we hard code a path to our Articles folder, which is not ideal. We might want to have it more customizable, especially if we want to reuse it from different parts of our application, or even Nx workspace.
[0:12] If we go to the Nx docs, Nx supports environment variables. It has support for different form of naming schemes which you can use, like basically, have a .local.env file or vice versa, or just an env file.
[0:27] You can have it within an application, or also at the workspace root level. Depending on where you place it, it would be injected just like here, if you start MyApp, while if you have it at the root level of the workspace, it would be injected into all applications.
[1:05] Which one you're going to use really depends on your use case. In our case, since that Articles folder is our global thing which different applications might use, and it is not just local for our Next.js application which we have in here, we might want to create here just a .env file. In here, we pass the article Markdown path, and we give it a value.
[1:28] Once we have that, we can then go in here and replace this piece here with process.env.articlemarkdown path. Now, if we start our server, we can go and check whether it still works. If we go to localhost, we see that it still renders the page. It means it probably was able to read the actual location of the folder from the environment variable.