Next.js File Structure and Important Info.

AbdulSamad Olagunju / January 08, 2022

12 min read

Tutorial

I will go over most of the files in my website.

If you want a more in-depth explanation on how to create a website and host it, look at these YouTube videos. Benjamin Carlson Tutorials:

  1. Making a Blog With Next.js
  2. Making a Blog with Next.js

I learned a lot about the structure of React and Next.js from this youtuber Benjamin Carlson, and I think this is a great resource for anyone who wants to get started in web development but doesn’t want to start learning from the ground up.

If you want to start learning from the ground up, I suggest getting the fundamentals of JavaScript, CSS, and HTML down. These are programming languages that allow you to build a web application, but tools like React allow you to create websites with a lot more functionality much faster.

  1. HTML Tutorial
  2. CSS Tutorial
  3. JavaScript Tutorial
  4. React Tutorial
  5. Next.js Tutorial

Before you begin with React, I would suggest learning more about HTML, CSS, and JavaScript. If you’re impatient like me and you immediately want to get to the fun stuff, there may be gaps in your understanding, but it’ll probably feel more exciting.

I’ll try to explain how you can set up a quick page using this awesome Next.js setup.

Start by downloading VS Code, as this is the IDE I use for web development. Download VS Code using this video: Download VS Code

Then, you will need to download Node.js and set up your environment. This video can take you through setting up Node.js: Download Node.js

Now we can create our first webpage! Open VS Code and your terminal.

Now enter this into your terminal in VS Code: yarn create next-app

You now have your project, pretty easy right?

My Website

Let’s go over what a bunch of the files mean. These are the short notes I recorded when I tried to learn more about web development. They are not supposed to give you the full picture, but give you more support when you try to create your own project.

Package.json: Located in the root directory of the project, the package.json file serves as a blueprint for the project. It contains essential information like the project's name, version, scripts, and dependencies. The listed dependencies are vital for the project's functionality. This file enables tools like npm (which employs JavaScript and the command line) or yarn to initialize the project. It's also the reference point to explore the npm packages integrated into the codebase.

Yarn.lock: Locks down dependencies in package.json file, so, if the dependency is changed by creator, you don’t get different dependencies. This prevents unintended changes in the imported dependencies, preserving the stability of the project.

.gitignore: While Git monitors changes in files, the .gitignore file explicitly specifies which files Git should ignore. By listing these files, you can keep sensitive or irrelevant files out of version control, thereby focusing on the essential components that need tracking.

Theme.js: How you want your fonts to look like, etc. The styling is imported from Chakra UI. The inclusion of const overrides ensures a consistent design across the fonts, replacing the default fonts typically used with Node.js.

Prism.js: Styling for the code displayed on the site.

Public: The designated space for storing images and the sitemap.

Lib/mdx.js: Within this file, mdx.js, a connection is established with MDX files using the renderToString function from next-mdx-remote. An object is created for each blog post. The object also presents information about word count and reading time, along with the slug (another name for dynamic URL). The integration of gray-matter helps parse the Markdown file into a frontmatter and content variable. The usage of process.cwd() retrieves the working directory of the Node.js file, so we can get the names of the Markdown files. The export async segment relates to scheduling code execution, as retrieving all of the files should occur on a different thread so the JavaScript main thread is not blocked. rehype and remark are employed for handling headings and code titles. The .reduce function executes the reducer function, which appears to involve adding MDX files to the blog. This segment essentially compiles the URLs of all MDX files. get static props facilitates retrieval of each blog post, with the data passed to MDXContent through props. The context mechanism appears to convey data collectively, bypassing the need to individually pass each prop.

Layouts/blog.js: This is the standard design of each blog page. blog.js augments the design of blog posts. It adds the date, avatar, and container component for styling. The slug is connected to MDX files within the data folder, resolving the file path.

Layout/simplestats.js: The same role as the layout for blog.js. In the new version of abneuro, I removed this file as it was unnecessary. I just passed the name of the other markdown folder if I had another set of posts.

/data: Containing markdown files for both simplestats and blog pages, the /data directory houses the blog posts.

Components/BlogPost.js & Components/SimpleStatsPost.js: These components employ colormode to establish text color for both light and dark modes. Information from the respective posts is integrated and passed to the blog layout. The blog layout is linked to the slug (URL).

Components/Footer.js: Footer.js establishes a connection with the index and adds links for navigation.

Components/DarkModeSwitch: This component employs the Chakra UI dark mode icon to facilitate switching between light and dark modes.

Components/Container: The default page layout is defined, with the children component encapsulating the page content. Additionally, the footer is imported and placed at the end of the container.

Components/MDXComponents: This component maps the markdown elements to react components, introducing new styles to the Markdown default element structure. For example, you can modify the paragraph tag and extend the style of the paragraph tag.

Pages/api/hello.js: Serving as a simple API router using JSON, hello.js is responsible for handling API requests. It is the default Next.js api route.

Pages/blog/[slug].js: This page establishes URLs for markdown files, allowing the creation of multiple markdown files connected to the blog page. It utilizes dynamic routing and involves the Next.js router to present dynamic routes to users. The router.query function extracts dynamic route parameters. The paths are mapped to getStaticPaths, focusing on a single requested blog post. The page styling is enhanced through the application of plugins.

Pages/simplestats/[slug].js: Same as Pages/blog/[slug].js but links to posts in simplestats. The animation for individual blog pages is passed to the element encapsulating the container for each blog post using animate.css.

Pages/_app.js: The entry point to the app, _app.js imports MDXComponents, wrapping it within the Components structure. The entire application is enveloped in Chakra UI. Additionally, the nprogress library is employed to display a progress bar.

Pages/_document.js: Overrides the default Next.js document file, incorporating a Google Analytics script for tracking page views.

Pages/blog.js: This page outlines the appearance of the blog page that shows a list of the blog posts. It presents the number of posts using the .length property, incorporates a search icon, retrieves posts from the blog, sorts them by publication date, and utilizes tools from Chakra UI.

Pages/contactme.js: A straightforward "Contact Me" JavaScript file housing a form for user subscriptions. The subscription process is facilitated through Mailchimp. The inclusion of a p5.js iframe adds to the page's functionality.

Pages/index.js: The root of the website, index.js is the first page users encounter upon accessing the URL. The page transition employs animate.css, while the container component is imported for page layout. Chakra UI contributes to the user interface and styling. An animated hand crafted from keyframes is featured, and react-responsive ensures a polished appearance on mobile devices. The bubbles are generated using react-tsparticles, a typewriter effect enhances text display, and the techstack is imported from components. Furthermore, a tailored footer is created specifically for mobile screens.

Pages/simplestats.js: Similar to Pages/blog.js.

Some important information:

  1. Use export default function with arrow notation to define your functions in your pages, then import with notation.
  2. In BlogPost.js, you pass you posts into the variable props using getStaticProps, and then you format the posts with Chakra UI, and format it in a way that lets you use links to specific individual blog posts.
  3. To streamline subscriber management, integrate the Mailchimp API to connect subscribers to your mailing list.
  4. .env.local is where you say what kind of environment variables you use, store the environment variables on Vercel so they can’t be taken from your GitHub repository.
  5. Asynchronous functions load before they fully execute, so they are valuable when you want to gather data from files before using that data.
  6. _App.js and document.js allow you to override default Next.js template and format your files the way you want to.
  7. getStaticProps will fetch your blog posts.
  8. You sort the blog posts by the date they were published.
  9. getAllFilesFromFrontMatter allows you to get all of your mdx files, mdx is same as md but it lets you use React components.
  10. use fs in getAllFilesFromFrontMatter to read your directory blog in the folder data, then you read the specific mdx file using grey matter, return mdx data and URL.
  11. To get a specific blog post, we use our dynamic [slug].js, you read values/files in function using getStaticProps, then use GetFileBySlug from mdx.js to fetch mdx file.
  12. Use await renderToString to get content from file, then you forward that to MDXComponents so it can be rendered to HTML.
  13. Return reading time, etc to make page look good.
  14. getStaticPaths: tells application about different URLS in website, fallback false so that if URL doesn’t exist, return out 404 page.
  15. const content = hydrate
    • hydrate makes components/content interactable with mdx
  16. In Container.js, remember to add meta tags for seo.
  17. For viewcounter, use viewcount api and swr (remote data fetching), you need a Firebase database.
  18. useColorMode interacts with darkmode and sets the color of page.
  19. Children passed in container after formatting done.
  20. If you use const function, make sure you use export default.
  21. async callback executes when file loading has completed, requires callback function for that reason.
  22. fs.readdirSync
    • returns the file name array with data of your file, but it will stop any further execution of your code until the read process ends., synchronous
  23. files.reduce
    • performs a function on all elements in array
  24. path.join
    • var path = require('path');
    • var x = path.join('Users', 'Refsnes', 'demo_path.js');
    • you end up getting: Users\Refsnes\demo_path.js
    • … turns array into individual elements, makes it easier to edit or read what is in array

Some more important information:

  1. The DOM helps your browser understand what it should show on your screen. It is like an address book, and every element in the DOM has a unique ID. The DOM only registers elements with ID tags. React creates a virtual DOM.
  2. ReactJS is a library, and it allows you to combine JavaScript and HTML. A DOM is like a tree, and it represents the connections between different tags. React allows you to easily manipulate the DOM by creating a Virtual DOM, and it can take in any updates made by the user. It can then quickly update the actual DOM, without all of the headaches and loss of speed involved when you directly manipulate the DOM.
  3. const { id } = router.query, gets the individual id
  4. export const getServerSideProps, async function, get your data, return props
  5. get StaticProps & GetStaticPaths get posts at build time, faster, getStaticPaths gets all posts as paths object
  6. const res gets data, then you make another variable that you set equal to await res.json to get json object
  7. .next folder has server
  8. Create static website with npm run build and put && next export to build
  9. In api, make sure res.status(200), makes sure connection is good
  10. Nextjs is react framework for production, easier to implement react components => Simplifies building react application, No need for 3rd party router, HTML generated in advance, Can create api
  11. React is declarative, react dom library builds actual UI, tell react what to do, it gets it done, you don’t have to specify steps
  12. CSS stands for cascading style sheets
  13. Stuff in body tag gets rendered to browser
  14. Head tag is extra info for website that goes at top of browser, head not rendered on page
  15. HTML grabs what works, standardizes it
  16. DOM: elements called tags tell browser what content we have, nested organization, familial relationship, tags on same level siblings, some tags parents and some tags children
  17. The DOM isn’t the code you write, the DOM (Document object modifier) is the result of your code, final output of your browser
  18. DOM can be manipulated after the browser renders it by javascript
  19. All html tags can carry attributes
  20. Heading, paragraph, anchor, list, horizontal rule, image, division tag
  21. Inline (element in same line) and block (new line) elements
  22. Css has selector and declaration
  23. Internal styles are defined within the style element, inside the head section of an HTML page
  24. . prefix means css element is for class
  25. Library is collection of functions that are reusable
  26. React.js imported in with node
  27. Higher order functions make code more reusable, put functions in functions

Wow, that was a lot of information. The article wasn't really that organized, but hopefully it helps you understand more about what is going on behind the scenes.

To learn more about web development, you can also take a look at these websites:

  1. https://brianlovin.com/writing/how-my-website-works
  2. https://www.benjamincarlson.io/
  3. https://leerob.io/

Thanks for reading!