🚏 Routes for Next.js

Overview

next-route-map 🚏

npm version CI

next-route-map allows you to define a route map. It automatically generates page modules that forward original modules in build time. Focus on domain, not foldering.

cover

Background

Next.js provides a consistent way to structure and organize pages. It is very intuitive and easy to use. However, when it comes to a larger application with many business domains, the file system based routing can cause several problems.

First, since it is strongly coupled to the file system, a file name can only represent a piece of url path rather than what it actually does. The larger application becomes the file names should be easier to understand. For example, DashboardPage.tsx is much easier to understand than pages/index.tsx. UserSearchPage.tsx is better than pages/users.tsx.

Second, pages/ directory can only contain page modules so you have to place related modules such as components and hooks in other directory. It means that your project will have two directory trees: one starting from pages/ and the other starting from src/. Same domain files are better to be in the same folder. For example, the second one is more organized that the first one.

pages/
  products/
    [id].tsx
products/
  components/
    Thumbnail.tsx
products/
  ProductDetailPage.tsx
  components/
    Thumbnail.tsx

At a glance

With next-route-map you can separate the page modules from routing. It automatically generates page modules from routing file.

Before 🤔

pages/
  index.tsx
  products/
    index.tsx
    [id].tsx
  orders/
    index.tsx
    [id].tsx
products/
  components/
    Thumbnail.tsx
orders/
  hooks/
    usePlaceOrder.ts

After 😊

home/
  HomePage.tsx
products/
  ProductListPage.tsx
  ProductDetailPage.tsx
  components/
    Thumbnail.tsx
orders/
  OrderListPage.tsx
  OrderDetailPage.tsx
  hooks/
    usePlaceOrder.tsx

(auto generated)
pages/
  index.tsx --> home/HomePage.tsx
  products/
    index.tsx --> products/ProductListPage.tsx
    [id].tsx --> products/ProductDetailPage.tsx
  orders/
    index.tsx --> orders/OrderListPage.tsx
    [id].tsx --> orders/OrderDetailPage.tsx

How it works

next-route-map finds all page modules from the project and creates corresponding forwarding modules in the page directory. The forwarding modules look like:

export { default } from '../src/products/ProductDetailPage'

When the page module contains magic functions like getStaticProps or getServerSideProps it will automatically export them as well.

export { default, getServerSideProps } from '../src/products/ProductDetailPage'

Getting started

  1. Add routes.config.js file to your project. See the Options for detail API usage.

    module.exports = {
      pagesDir: './pages',
      routes: {
        '/': './src/home/HomePage.tsx',
        '/products': './src/products/ProductListPage.tsx',
        '/products/[id]': './src/products/ProductDetailPage.tsx',
        '/orders': './src/orders/OrderListPage.tsx',
        '/orders/[id]': './src/orders/OrderDetailPage.tsx',
        '/404': './src/errors/404.tsx',
      },
      preservePaths: [
        '_app.tsx',
        '_document.tsx',
      ],
      logger: console,
    }
  2. Add next-route-map command to your package.json.

      "scripts": {
    -   "dev": "next dev",
    -   "build": "next build",
    +   "dev": "next-route-map && next dev",
    +   "build": "next-route-map && next build",
        "start": "next start",
        "lint": "next lint"
      },
  3. Then the plugin will generate the proper page modules on $ yarn build or $ yarn dev.

    • ./pages/index.ts
    • ./pages/products/index.ts
    • ./pages/products/[id].ts
    • ./pages/orders/index.ts
    • ./pages/orders/[id].ts
    • ./pages/404.ts

    It is safe to add the pages directory to .gitignore.

    /pages/*
    !/pages/_app.tsx
    !/pages/_document.tsx

Options

baseDir

A Next.js project directory. Use this option if your Next.js application is located in somewhere else. Defaults to cwd.

pagesDir

A directory to generate pages. This value may be ./pages or ./src/pages.

routes

A route map for url paths and page file paths.

For example:

{
  '/': './src/home/HomePage.tsx',
  '/products': './src/products/ProductListPage.tsx',
  '/products/[id]': './src/products/ProductDetailPage.tsx',
  '/orders': './src/orders/OrderListPage.tsx',
  '/orders/[id]': './src/orders/OrderDetailPage.tsx',
  '/404': './src/errors/404.tsx',
}

preservePaths

Paths to preserve on clean. Use this option if there is a non-forwarding module in the pages directory. The paths are relative to pages directory.

For example:

['_app.tsx', '_document.tsx']

Note that this option does not guarantee that the path is not ignored from .gitignore. If you makde the pages directory be ignored, you need to explicitly add a rule.

  # next.js
  /pages/*
+ !/pages/_app.tsx
+ !/pages/_document.tsx

logger

If you want log build output, use console.

Installation

  • Using Yarn:
    $ yarn add next-route-map --dev
  • Using npm:
    $ npm install next-route-map --save-dev

License

react-route-map is under MIT license. See the [LICENSE] file for more info.

You might also like...

Bun-Bakery is a web framework for Bun. It uses a file based router in style like svelte-kit. No need to define routes during runtime.

Bun-Bakery is a web framework for Bun. It uses a file based router in style like svelte-kit. No need to define routes during runtime.

Bun Bakery Bun-Bakery is a web framework for Bun. It uses a file based router in style like svelte-kit. No need to define routes during runtime. Quick

Dec 6, 2022

Generate translated routes for your qwik project.

qwik-translate-routes Generate translated routes for your qwik project. Installation // npm npm install -D qwik-translate-routes // yarn yarn add -D q

Dec 28, 2022

🖼️ Image proxy for Next.js. Makes it possible to use dynamic domains in next/image component.

Next.js Image Proxy Image proxy for Next.js. Makes it possible to use dynamic domains in next/image component. ❔ Motivation This library makes it poss

Dec 1, 2022

💻 A simple Create Next App template to start your projects with Next.js, TypeScript, ESLint, Prettier and other tools.

⚡ Next Typescript Template ⚡ A simple Create Next App template to start your projects with Next.js, TypeScript, ESLint, Prettier and other tools. Quic

Nov 23, 2022

A fullstack next.js template with all the fun stuff like next auth, mongodb, prisma, chakra ui

A fullstack next.js template with all the fun stuff like next auth, mongodb, prisma, chakra ui

Welcome to FullStack Next.js template 👋 A fullstack next.js template with all the fun stuff like next auth, mongodb, prisma, chakra ui ✨ Demo Tech Ne

Oct 16, 2022

This is a Next.js project bootstrapped with create-next-app.

Getting Started First, run the development server: npm run dev # or yarn dev Open http://localhost:3000 with your browser to see the result. You can s

Dec 5, 2022

💯 Materials to help you rock your next coding interview

Tech Interview Handbook Credits: Illustration by @leftaligned Read on the website Black Lives Matter. Support the Equal Justice Initiative What is thi

Dec 29, 2022

A curated collection of common interview questions to help you prepare for your next interview.

A curated collection of common interview questions to help you prepare for your next interview.

30 Seconds of Interviews A curated collection of common interview questions to help you prepare for your next interview. This README is built using ma

Jan 7, 2023

A github action that provides detailed bundle analysis on PRs for next.js apps

A github action that provides detailed bundle analysis on PRs for next.js apps

Next.js Bundle Analysis Github Action Analyzes each PR's impact on your next.js app's bundle size and displays it using a comment. Optionally supports

Dec 27, 2022
Releases(0.3.1)
Owner
Suyeol Jeon
A lazy developer 😴 I write many code to write less code.
Suyeol Jeon
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
next-graphql-server is a library for building production-grade GraphQL servers using Next.js with API Routes

next-graphql-server next-graphql-server is an easy to use Next.js library for creating performant GraphQL endpoints on top of Next.js API Routes. Star

Jakub Neander 82 Nov 21, 2022
Avoid CORS issues by using API Routes from Next.js

CORS Demo Avoid CORS issues by using API Routes from Next.js. Get Started Clone the repo git clone [email protected]:gregrickaby/cors-demo.git CD into co

Greg Rickaby 2 Sep 30, 2022
🚏 Routes for Next.js

next-route-map ?? next-route-map allows you to define a route map. It automatically generates page modules that forward original modules in build time

Suyeol Jeon 26 Sep 24, 2022
Framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. 🗺️ Remix driver included. 🤟

About routes-gen is a framework agnostic CLI tool for routes parsing and generation of a type-safe helper for safe route usage. Think of it as Prisma,

Stratulat Alexandru 192 Jan 2, 2023
SafeCycle—a tool that keeps cyclists safe. Gone are days of weaving through busy city streets, SafeCycle finds all the bike routes for you to ensure a smooth ride wherever you want to go.

Inspiration Biking—an everyday form of travel for students and professionals across the globe. On-campus, back home, and with the people that we know

Ryan Hu 2 May 2, 2022
generate pages from markdown files with dynamic routes, 0 effort, 0 boilerplate.

next-markdown Markdown Pages for Next.js Dynamic Routes. Blog Aware. Design Your Layout Made for people having a nextjs project in ❤️ with markdown wh

François Rouault 105 Oct 11, 2022
This plugin can be embedded in PHP application to give the web application specific routes/href

Routes Plugin PHP This plugin can be embedded in PHP application to give the web application specific routes/href location and for entering specific/l

Ifechukwudeni Oweh 7 Jul 17, 2022
Ready-to-use Remix + Tailwind CSS routes and components.

remix-blocks What is RemixBlocks? Ready-to-use Remix + Tailwind CSS routes, and UI components, all blocks: Are full-stack routes. Are independent of e

Alexandro Martínez 111 Jan 5, 2023