All Projects → revskill10 → Next Routes Middleware

revskill10 / Next Routes Middleware

Licence: mit
Universal Lambda Routing

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Next Routes Middleware

Next Apollo Auth
Authentication Boilerplate with Next.js and Apollo GraphQL
Stars: ✭ 159 (+329.73%)
Mutual labels:  nextjs, expressjs
Next Express Bootstrap Boilerplate
⚡️ JavaScript boilerplate for a full stack app built using React.js, Next.js, Express.js, react-bootstrap, SCSS and full SSR with eslint.
Stars: ✭ 102 (+175.68%)
Mutual labels:  nextjs, expressjs
Notion Clone
Stars: ✭ 2,048 (+5435.14%)
Mutual labels:  nextjs, expressjs
Builderbook
Open source web application to learn JS stack: React, Material-UI, Next.js, Node.js, Express.js, Mongoose, MongoDB database.
Stars: ✭ 3,015 (+8048.65%)
Mutual labels:  nextjs, expressjs
faeshare
MERN based social media web app made with the help of Next.js, Socket.io and TailwindCSS.
Stars: ✭ 37 (+0%)
Mutual labels:  nextjs, expressjs
cafecito
Cafecito es un proyecto hecho en Next.JS con Express.JS y MongoDB para recibir cafés ☕️ a modo de donaciones.
Stars: ✭ 95 (+156.76%)
Mutual labels:  nextjs, expressjs
uploading-files-react-node
Uploading files with React.js and Node.js
Stars: ✭ 33 (-10.81%)
Mutual labels:  nextjs, expressjs
nextjs-typescript-express-boilerplate
A next.js boilerplate app with Typescript and an Express API server
Stars: ✭ 30 (-18.92%)
Mutual labels:  nextjs, expressjs
Imgsquash
Simple image compression full website code written in node, react and next.js framework. Easy to deploy as a microservice.
Stars: ✭ 948 (+2462.16%)
Mutual labels:  nextjs
Checksheet Manager
Checksheet Manager for college checksheets. Created with AngularJS and Node/Express/MongoDB.
Stars: ✭ 31 (-16.22%)
Mutual labels:  expressjs
Generator Express Es6
Yeoman generator for Express.js
Stars: ✭ 28 (-24.32%)
Mutual labels:  expressjs
Practical Clean Ddd
A simplified and effortless approach to get started with Domain-driven Design, Clean Architecture, CQRS, and Microservices patterns
Stars: ✭ 28 (-24.32%)
Mutual labels:  nextjs
Oauth2orize resource owner password example
This is an example of the oAuth resource owner password flow using oauth2orize, express 4 and mongoDB.
Stars: ✭ 31 (-16.22%)
Mutual labels:  expressjs
Golazon
Football data mnmlist way. Built with Next.js and Ruby.
Stars: ✭ 28 (-24.32%)
Mutual labels:  nextjs
Node Production
Take Your Node.js Project to The Production Environment (VPS/Dedicated Server).
Stars: ✭ 35 (-5.41%)
Mutual labels:  expressjs
Socket Click Example
Node + Express + Socket.io button click example
Stars: ✭ 28 (-24.32%)
Mutual labels:  expressjs
Blog.hellorusk.net
Tech Blog
Stars: ✭ 28 (-24.32%)
Mutual labels:  nextjs
Wordpress Api Nextjs Theme
A workshop on creating a WordPress theme with React and Next.js for WordCamp Montreal
Stars: ✭ 36 (-2.7%)
Mutual labels:  nextjs
Foodeazy
Stars: ✭ 34 (-8.11%)
Mutual labels:  expressjs
Viraljs
Express.JS middleware to enable P2P distribution for your app. Your decentralized CDN made easy.
Stars: ✭ 952 (+2472.97%)
Mutual labels:  expressjs

Next Routes Middleware

npm version

Universal Lambda Routing for Next.JS application

Roadmap for 4.0.0

  1. Integrate with existing now.json in now.config.js for better integration with existing ecosystem
  2. Provide @now/node to replace @now/next (Next V8 provides a serverless lambda out of the box)

Demo

Demo

Installation

npm i --save next-routes-middleware

Features

  • Replicate next.js for Now V2 config to develop locally.
  • Support named regular expressions used in routes.
  • Allow custom routes handling with all Express.js http methods.
  • Client-side routing
  • Compiling to Now V2 compatible JSON config

Usage

Step 1: Create your own now.config.js:

const buildTypes = [
  "@now/next",
  "@now/static"
]
const builds = [
  {
    src: "next.config.js", use: buildTypes[0]
  },
  {
    src: "static", use: buildTypes[1]
  }
]

const nextRoutes = ['/about'].map(function(item, index) {
  return {
    src: item,
    dest: item,
    build: buildTypes[0],
  }
})

const deployConfig = {
  version: 2,
  name: "next-routes-middleware",
  public: true,
  alias: "next-routes-middleware"
}


const patterns = {
  first: "(?<first>.*)",
  uuid: "(?<uuid>[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}){1}",
  slug:"(?<slug>[^/]*)",
  year:"(?<year>[0-9]{4})",
  month:"(?<month>[0-9]{2})",
  day:"(?<day>[0-9]{2})"
}

const routes = [
  {
    src: "/favicon.ico",
    dest: "static/favicon.ico",
    build: buildTypes[0],
  },
  ...nextRoutes,
  { 
    src: `/w/${patterns.first}`, 
    dest: "/work?slug=${first}",
    build: buildTypes[0],
  },
  { 
    src: `/resource/${patterns.uuid}`, 
    dest: "/complex?id=${uuid}",
    build: buildTypes[0],
  },
  { 
    src: `/t/${patterns.slug}/${patterns.year}-${patterns.month}-${patterns.day}`, 
    dest: "/more_complex?day=${day}&month=${month}&year=${year}&slug=${slug}" ,
    build: buildTypes[0],
  },
  { src: "/", dest: "/index", build: buildTypes[0], }
]


module.exports = {
  ...deployConfig,
  patterns,
  builds,
  routes,
}

Note: You can skip step 2 by using now-dev-cli, which will run this custom server for you.

Step 2: Using next-routes-middleware in your custom server.js

const express = require('express')
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const routesMiddleware = require('../../index')
const port = parseInt(process.env.PORT, 10) || 3000
const config = require('./now.config.js')
app.prepare().then(() => {
  const server = express()
  const prefix = ""
  routesMiddleware({server, app, config, prefix})
  server.listen(port, (err) => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})


Step 3: Using in pages/more_complex.js

import {withRouter} from 'next/router'
import Nav from '../components/nav'
const Page = ({router}) => {
  const {
    query
  } = router

  const {day, month, year, slug} = query
  return (
    <>
    <Nav />
    <div>Slug is {slug}</div>
    <div>You requested {year}-{month}-{day}</div>
    </>
  )
}

export default withRouter(Page)

Customization and Overriding Routes

Suppose you want to do something else beyond rendering, you can provide custom routes handler like this

customRoutes.js

function customRoutes(nextRoutes) {
  return {
    '/service-worker.js': function({app, req, res, join, dev}) {
      const filePath = dev ? join(__dirname, '../static', 'service-worker.dev.js'): join(__dirname, '../static', 'service-worker.js')
      app.serveStatic(req, res, filePath)
    },
    '/favicon.ico': function({app, req, res, join}) {
      const filePath = join(__dirname, '../static', 'favicon.ico')
      app.serveStatic(req, res, filePath)
    },
    '/static/wasm/*': function({app, req, res, next, handle, pathname}) {
      res.setHeader('Content-Type', 'application/wasm')
      handle(req, res, parsedUrl)
    },    
    '/': function({app, req, res, isMobile, query}) {
      if (!isMobile) {
        app.render(req, res, '/index', {phone: false, ...query })
      } else {
        app.render(req, res, '/index', {phone: true, ...query})
      }
    },    
    ...nextRoutes,
    '*': function({handle, req, res, parsedUrl}) {
      handle(req, res, parsedUrl)
    },
  }
}

module.exports = customRoutes

Then use in your custom server.js

const customRoutes = require('./customRoutes')
routesMiddleware({server, app}, customRoutes)

Compiled now config file

This is the compiled Now config file

{
  "version": 2,
  "name": "next-routes-middleware",
  "public": true,
  "alias": "next-routes-middleware",
  "patterns": {
    "first": "(?<first>.*)",
    "uuid": "(?<uuid>[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}){1}",
    "slug": "(?<slug>[^/]*)",
    "year": "(?<year>[0-9]{4})",
    "month": "(?<month>[0-9]{2})",
    "day": "(?<day>[0-9]{2})"
  },
  "builds": [
    {
      "src": "next.config.js",
      "use": "@now/next"
    },
    {
      "src": "static",
      "use": "@now/static"
    }
  ],
  "routes": [
    {
      "src": "/favicon.ico",
      "dest": "static/favicon.ico"
    },
    {
      "src": "/about",
      "dest": "/about"
    },
    {
      "src": "/w/(?<first>.*)",
      "dest": "/work?slug=$first"
    },
    {
      "src": "/resource/(?<uuid>[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}){1}",
      "dest": "/complex?id=$uuid"
    },
    {
      "src": "/t/(?<slug>[^/]*)/(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})",
      "dest": "/more_complex?day=$day&month=$month&year=$year&slug=$slug"
    },
    {
      "src": "/",
      "dest": "/index"
    }
  ]
}

Usage with next/link and styled-components for client-side routing

styled-link.js

import Link from 'next/link'
import styled from 'styled-components'
import mkLink from 'next-routes-middleware/get-client-link'
import config from '../now.config.js'
const getClientLink = mkLink(config)

const NextLink = ({href, className, children, ...rest}) => {
  const as = getClientLink(href)
  return (
    <Link href={as} as={href} {...rest}>
      <a className={className} href={as}>{children}</a>
    </Link>
  )
}

const StyledLink = styled(NextLink)`
  color: #067df7;
  text-decoration: none;
  font-size: 13px;
`

export default StyledLink

Usage on client-side

import StyledLink from './styled-link'
<Li>
  <StyledLink href='/w/test' passHref>Work</StyledLink>
</Li>
<Li>
  <StyledLink prefetch href="/resource/202eb9d7-feb3-407c-922e-e749159cb3ec" passHref>Resource</StyledLink>
</Li>
<Li>
  <StyledLink prefetch href="/t/hello-world/1999-12-31" passHref>More resource</StyledLink>
</Li>
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].