Git Product home page Git Product logo

next.js's Introduction

Next.js

Getting Started

Used by some of the world's largest companies, Next.js enables you to create full-stack web applications by extending the latest React features, and integrating powerful Rust-based JavaScript tooling for the fastest builds.

Documentation

Visit https://nextjs.org/docs to view the full documentation.

Community

The Next.js community can be found on GitHub Discussions where you can ask questions, voice ideas, and share your projects with other people.

To chat with other community members you can join the Next.js Discord server.

Do note that our Code of Conduct applies to all Next.js community channels. Users are highly encouraged to read and adhere to them to avoid repercussions.

Contributing

Contributions to Next.js are welcome and highly appreciated. However, before you jump right into it, we would like you to review our Contribution Guidelines to make sure you have a smooth experience contributing to Next.js.

Good First Issues:

We have a list of good first issues that contain bugs that have a relatively limited scope. This is a great place for newcomers and beginners alike to get started, gain experience, and get familiar with our contribution process.

Authors

A list of the original co-authors of Next.js that helped bring this amazing framework to life!


Security

If you believe you have found a security vulnerability in Next.js, we encourage you to responsibly disclose this and NOT open a public issue. We will investigate all legitimate reports. Email [email protected] to disclose any security vulnerabilities. Alternatively, you can visit this link to know more about Vercel's security and report any security vulnerabilities.

next.js's People

Contributors

alexkirsz avatar arunoda avatar balazsorban44 avatar delbaoliveira avatar feedthejim avatar forsakenharmony avatar greenkeeper[bot] avatar handtrix avatar hanneslund avatar huozhi avatar ijjk avatar jankaifer avatar janpot avatar jridgewell avatar kdy1 avatar kwonoj avatar leerob avatar lfades avatar nkzawa avatar padmaia avatar rauchg avatar shuding avatar sokra avatar styfle avatar timer avatar timneutkens avatar vercel-release-bot avatar wbinnssmith avatar wyattjoh avatar ztanner avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

next.js's Issues

Application Layout?

In the React context, when building an app I'm used to the concept of containers and components. It appears to me that "pages" are somewhat equivalent to containers within next.js.

Is there a recommended way to add an application layout container such that I could specify for example global <Header/> and <Footer/> components with the router determining which content to display within (the page)? Similar to how the popular react-router package match function can be configured on the server.

Using the next.js default router and pages folder as is, to achieve this do I have no option but to duplicate <Header/> and <Footer/> across all pages?

Proposition: parameters in URL

I think it would be great to have parameter in URL functionality (for example /users/:id) while still keeping the simplicity of next itself.

My proposition is to do this for structure:

pages/
  index.js
  users/
    _id.js

id.js will be seen as a parameter path and will receive id as prop. You could also go further and make it like this to map /users/:id/friends/:friendid:

pages/
  index.js
  users/
    _id/
      index.js
      friends/
        _friendid.js

If the id is not specified (eg. /users/) then we'll first check if there is an index.js and otherwise use _id.js.

I created this issue to see if others are interested in this and to see what everyones thoughts/feedback is on this. I'm willing to build this if this is a wanted feature! 😄

Handling images

I'm just wondering, if I want to use an image in my component how should I handle it ? and where the image should be stored ? Couldn't find that in your docs or examples.

Custom server logic / routing

next -s server.js

or in package.json:

{
  "next": {
    "serverHandler": "./server.js"
  }
}

Let's say you want to override the default mapping between filesystem and route, you could set up something like this:

const { renderComponent } = require('next/server')
module.exports = ({ path, req, res }) => {
  if ('/a' === path) {
    return renderComponent(req, './b')
  }
}

The function would receive a context object with the following properties (as far as I have thought about it):

  • path the intended path of the request. This is so that if we request /a.json or /a, the path is still /a, which simplifies the logic for the programmer
  • req the original request from node
  • res the original response from node

The return value can be a Promise. If undefined is returned, it performs the default behavior.
This file provides an opportunity to short-circuit (like send a 301), add global security / authentication requirements, etc.

[1] We might or might not want to transpile this file. Since it's "server-only", I think it's ok to assume it just supports whatever the version of Node.js you're running.

first readme example breaks

screen shot 2016-10-25 at 1 20 17 pm

$ node -v
v7.0.0
$ npm -v
3.10.8
$ tree . -L 2
.
├── package.json
└── pages
    └── index.js
$ cat pages/index.js 
import React from 'react'
export default () => {
  <div>Welcome to next.js!</div>
}
$ cat package.json 
{
  "name": "next-play",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "next": "^1.0.0"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "next"
  },
  "author": "",
  "license": "ISC"
}
$ npm start

> [email protected] start /Users/ext.dmosher/code/next-play
> next

> Ready on http://localhost:3000
Warning: Component(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
{ Invariant Violation: Component(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
    at invariant (/Users/ext.dmosher/code/next-play/node_modules/fbjs/lib/invariant.js:38:15)
    at ReactCompositeComponentWrapper.mountComponent (/Users/ext.dmosher/code/next-play/node_modules/react/lib/ReactCompositeComponent.js:194:121)
    at Object.mountComponent (/Users/ext.dmosher/code/next-play/node_modules/react/lib/ReactReconciler.js:47:35)
    at ReactCompositeComponentWrapper.performInitialMount (/Users/ext.dmosher/code/next-play/node_modules/react/lib/ReactCompositeComponent.js:370:34)
    at ReactCompositeComponentWrapper.mountComponent (/Users/ext.dmosher/code/next-play/node_modules/react/lib/ReactCompositeComponent.js:257:21)
    at Object.mountComponent (/Users/ext.dmosher/code/next-play/node_modules/react/lib/ReactReconciler.js:47:35)
    at /Users/ext.dmosher/code/next-play/node_modules/react/lib/ReactServerRendering.js:46:36
    at ReactServerRenderingTransaction.perform (/Users/ext.dmosher/code/next-play/node_modules/react/lib/Transaction.js:138:20)
    at renderToStringImpl (/Users/ext.dmosher/code/next-play/node_modules/react/lib/ReactServerRendering.js:44:24)
    at renderToString (/Users/ext.dmosher/code/next-play/node_modules/react/lib/ReactServerRendering.js:74:10) name: 'Invariant Violation', framesToPop: 1 }

Add Redux example to README

We want to have an example of global state. Since Redux is King of Global State®, let's go with a tiny redux example.

See Slack conversation for reference

Vue.js Support?

Would you plan to support vue.js as an alternative to react?

Custom webpack config

It'd be nice to add hooks for webpack, and describe on the README (similarly to #26) how to for example add require('./something.css') support.

Support static site rendering

Looking at the overall project structure, this seems like a rather easy step on your roadmap. Maybe someone from the team can provide a good starting point for contributors?

Style isolation through Shadow DOM

For the vast number of users who with very good reasons reject CSS-in-JS, we could support something like this:

import Head from 'next/head'
import shadow from 'next-shadow'
export shadow(() => (
  <footer>
    <div>hi <span>world</span></div>
    <style>{`
      div span {
        /* this won't conflict with any other element anywhere,
            including spans from nested components */
        color: red
      }
    `}</style>
  </footer>
))

In the future, if we find a way of making this work with server-rendering, we could make every single component a custom element with built-in isolation capabilities out of the box, no shadow() wrapping needed. If you want global effects, you can use <Head>, otherwise everything is isolated.

This would put CSS-in-JS and full CSS support on equal ground, both supported, both with pros-and-cons and great performance.

The problems:

  • Limited browser support for now
  • Is this actually doable?
    • Perhaps base it on react-shadow
    • What's the server-rendering story of custom elements? Do they require JS execution for the elements registration? Could be slow and impractical
  • Are there performance drawbacks?

Better JSX

JSX as used with most React projects comes with a very obscure situation
The following doesn't work:

export default () => <div />

You need to import React from 'react' so that the JSX transformation to React.createElement, which appears nowhere in the source, works.

How do we fix this?

  • Perhaps transform to Next.createElement which invokes the right adapter (#20). Downside: extra invocation
  • Switch to a JSX compilation that uses plain JavaScript objects and hope that React adopts it (and perhaps other adapters (#20))

Identity-based idempotency support for `next/head`

We can have a declarative way of ensuring an element appears at-most-once in the <head>. We de-dupe based on the id attribute of an element. It could also be key but not sure if that interferes with React internals.

<Head>
  <style id="woot">{`
    /* this element will be appended at-most-once */
    /* even if it appears in multiple components */
  `}</style>
</Head>

Inconsistent versioning for devDependencies

Some of the modules are specified with a caret while some are not. Is this intentional?

"devDependencies": {
    "babel-eslint": "^7.0.0",
    "babel-plugin-transform-remove-strict-mode": "0.0.2",
    "benchmark": "2.1.1",
    "gulp": "3.9.1",
    "gulp-ava": "0.14.1",
    "gulp-babel": "6.1.2",
    "gulp-benchmark": "^1.1.1",
    "gulp-cached": "1.1.0",
    "gulp-notify": "2.2.0",
    "husky": "^0.11.9",
    "run-sequence": "1.2.2",
    "standard": "^8.4.0",
    "webpack-stream": "3.2.0"
  }

`next-build` should warn about existing `.next`

This way, people can avoid accidents and side-effects. Typically if you're starting a next build you want to start from a clean slate.

Displaying a simple warning in stdout is probably a good idea.

npm install -g next?

Following the readme example, it indicates to install next with npm install next --save. I couldnt get the example to work this way.

zsh: command not found: next

Shouldn't this be npm install -g next so that the next command is global?

next:{cdn:true} is no work

{
  "name": "mistat",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "next": "latest"
  },
  "next":{"cdn":false}
}

when I run next build & next start or run next ,the cdn is not dispair,shall we style the cdn link in our service ?

Graceful shutdown

There appears to be no provision made in the Next code for terminating the application gracefully. I don't see any hooks into SIGTERM or SIGKILL events, and server/index.js doesn't offer a stop() function.

This means that any time the app receives a shutdown event from the host machine it will halt while in the middle of handling requests instead of waiting for the requests to complete and properly stopping the server.

This also makes it impossible to start and stop the server in integration tests.

Add CLI Usage

I expected next --help to be a thing:

❯ next --help
> Ready on http://localhost:3000
> Couldn't find a `pages` directory. Please create one under the project root

next build is currently undocumented. My goal was to discover its purpose without reading the code. 😛

Support for pluggable renderers

Like inferno or preact.

From the end user perspective, it would work as follows.
Configure package.json:

{
  "dependencies:" {
    "next": "x.y.z",
    "next-preact": "x.y.z",
    "preact": "x.y.z"
  }
}

Then we transform JSX to the pragma that, in this example, next-preact would need.
The rendering pipeline would similarly be pluggable.

Eventually support/use multiple React roots?

I noticed that one React root is used, while this is certainly the simplest solution, I'm curious if there's a plan to support or use multiple React roots?

In the current architecture with a single root, a client-side navigation blows away everything visible on the page and re-renders everything for the new route, including parts of the component tree that exist on both routes.

With multiple React roots, common site elements like a <header> could be in their own React root, and when the same page "region" exists between two routes the component tree won't need to be torn down and re-rendered during that client-side navigation. An architecture with multiple roots/regions would also allow the server to flush out to the response before waiting for the entire page to be rendered.

I imagine that when using Next, it'll be natural to break out common page-level UI component trees, like the site's header, and reuse it on all pages, similar to an "include", and at these page "region" boundaries there's an opportunity to use multiple React roots to speed up both server and client rendering.

So I'm mainly curious if this sort of thing might be part of Next in the future, or if the simplicity of one React root and re-rendering the entire page on client-side navigation is an explicit design decision for the framework?

Redux example UTC time

While running Redux example on server with UTC time set, I've got these errors in my browser console because of timezone differences:

next-dev.bundle.js:8985 Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:
(client) " data-reactid="1">15:03:39
(server) " data-reactid="1">12:03:39

Possible fix is to change Clock.js :13 from:

const format = t => `${pad(t.getHours())}:${pad(t.getMinutes())}:${pad(t.getSeconds())}`

to:

const format = t => `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`

CSS in header

Hello,

I'm trying to include a css resource using the Head component (it's a large css file, so I don't want to use glamor)

<Head>
  <meta charSet='utf-8'/>
  <meta name='viewport' content='initial-scale=1.0, width=device-width'/>
  <link rel="stylesheet" href="/static/css/application.css"/>
  <script defer src="/static/js/application.js"></script>
</Head>

Unfortunately by doing so, when I navigate to another page, the css gets unloaded and then loaded again causing the UI to kinda "flicker".

What's the NextJS way to deal with that use case?

Thank you.

Transform webpack-dev-server to Express server

Hi,

Will next provide a ability to allow us to embed our own Express.js middlewares / routers for handling server side logic, e.g. backend API.

We can have the following server/body-parser-urlencoded-middleware.js:

import bodyParser from 'body-parser-urlencoded'
export default bodyParser.urlencoded({ extended: false })

and also api-router.js:

import express from 'express'
const router = express.Router()

router.get('/',(req, res) => {
  res.send('Hello API')
})

export default router

And for next side will just grabbing all files under server/ directory,

If the filename ends with "middleware" then plug it like app.use(middleware())
If ends with "router" then extract the route, in the case above is app.use("/api", router) and we can request to the API in our next app.

Just a basic concept for open discussion, or is there any other method to implement API feature? Thanks.

Top-level app component and animated route transitions

Having animated route transitions would be nice, as this is one of the many benefits through client-side routing. Doing so should be left up to the user in my opinion (some people prefer CSS transitions over more fine-grained control with react-motion etc). As I understand it, one would need to modify the top-level App component.

The client entry file seems to look for a globally assigned __NEXT_DATA__.app variable but I can't find any documentation on that.

Route matching with params

Is there any support for route params like so?
/photos/:id

If not, how would that look with the proposed pages/*.js structure?

accessing parsed url in getInitialProps

As far as I can tell, the static getInitialProps doesn't provide a uniform way to access url params on the client and server. On the server, you can access req and parse the url yourself. On the client, we don't seem to have access to the route information within the getInitialProps function. The uses for this are fairly obvious, i think, such as loading a particular user profile based on an :id param, and so on. I'm also wondering if auth could somehow be implemented here too -- thought I'm less clear if that's the best API.

Hot code reloading checklist

Some example scenarios to check

  • After making a change, server-rendering works as expected (bug)
  • Errors render on the browser as well (with our existing style)
  • Works with path registration / unregistration.
    • If I go to /test and test.js doesn't exist, render 404. Creating it renders test.js
    • If I create test.js but with an error, we replace the 404 with an error
    • If test.js has an error but I remove it, render 404
  • Handle the scenario correctly where the user-created error.js has an error (fallback + console.error in main terminal is acceptable for this)
  • Hot code reloading of error.js works when rendering an error

how to work with stateful dependencies

First off, spot on! next.js is an awesome idea!

I tried the framework by hacking down an Index component which is hooked up to a firebase instance. Unfortunately the firebase library holds it's state internally, which brakes the component after performing a hard reload:

import React, { Component } from 'react';
import firebase from 'firebase';

class Index extends Component {
  constructor() {
    super();

    this.state = {
      users: []
    };
  }

  componentWillMount() {
    firebase.initializeApp({
      apiKey: '...',
      authDomain: '...',
      databaseURL: '...',
      storageBucket: '...',
      messagingSenderId: '...'
    });

    firebase.database().ref('/users/').on('child_added', data => {
      this.setState({
        users: [...this.state.users, data.val()]
      });
    });
  }

  render() {
    const { users } = this.state;

    return (
      <div>
        {users.map(user =>
          <div key={user.id}>{user.name}</div>
        )}
      </div>
    );
  }
}

export default Index;

Redux example error while running build

Redux example

next build
next start

Error in browser console:

VM3895:2 You are currently using minified code outside of NODE_ENV === 'production'. This means that you are running a slower development build of Redux. You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) to ensure you have the correct code for your production build.

Is there a way to use NODE_ENV === 'production' with Next.js build/start scripts?

next command not found

Hey!

Really cool project. I was just following the demo on the site and I did the following:

brew install node
mkdir foo
cd foo
npm init
npm install next ---save
mkdir pages
vim pages/index.js
next

and then !

command not found: next

shoot

oh..

./node_modules/next/dist/bin/next

that works.

I'm a noob JavaScript developer, should I have some sort of relative path setup for that?

Just a heads up, thanks!

Add default CDN

Per FAQ:

We intend for Next.js to be a great starting point for any website or app, no matter how small.

If you’re building a very small mostly-content website, you still want to benefit from features like lazy-loading, a component architecture and module bundling.

But in some cases, the size of React itself would far exceed the content of the page!

For this reason we want to promote a situation where users can share the cache for the basic runtime across internet properties. The application code continues to load from your server as usual.

We are committed to providing a great uptime and levels of security for our CDN. Even so, we also automatically fall back if the CDN script fails to load with a simple trick.

To turn the CDN off, just set { “next”: { “cdn”: false } } in package.json.

Document `next-prefetch`

next-prefetch is a substitute for <Link /> (builds on top of it) that:

  • By default prefetches the given component using a ServiceWorker
  • It would have an option prefetch={false} if you want to turn it off
  • It would have an option fallbackWorker={true} to fallback to a web worker if the browser doesn't support service workers.

This is the technique that we use at ▲ZEIT to make everything really speedy.
We need to extract it out of our impl or someone can write this from scratch.

Installing a service worker is pretty intrusive, so I don't think this is something we want in core. We can write it as a separate module.

Represent full HTML tree in a page

I've also been exploring this too. Definitely think this is the right direction forward. One simplification that I think can be made is to represent the entire HTML tree in the page, so instead of this:

export default () => <div>
  <Head>
    <meta content='my meta' />
  </Head>
  <h1>I can haz meta tags</h1>
</div>

With side-effect and DOM-reaching craziness, you could do something like this:

export default () => (
  <html>
     <head>
       <meta content='my meta' />
     </head>
     <body>
       <h1>I can haz meta tags</h1>
     </body>
  </html>
)

Implementation goes like this:

  • On the server, the whole tree will be rendered.
  • On the client, the html component reaches into the children, finds the first child in body and returns that.

Unknown plugin "transform-async-to-generator"

Platform: Linux (Arch) x86_64
node: v6.9.1
npm: 3.10.9

pages/index.js:

import React from 'react'
export default () => (
  <div>Welcome to next.js!</div>
)

when I run next I get:

ERROR in ./pages/index.js
Module build failed: ReferenceError: Unknown plugin "transform-async-to-generator" specified in "base" at 0, attempted to resolve relative to "/home/gk/projects/test/pages"
    at /usr/lib/node_modules/next/node_modules/babel-core/lib/transformation/file/options/option-manager.js:176:17
    at Array.map (native)
    at Function.normalisePlugins (/usr/lib/node_modules/next/node_modules/babel-core/lib/transformation/file/options/option-manager.js:154:20)
    at OptionManager.mergeOptions (/usr/lib/node_modules/next/node_modules/babel-core/lib/transformation/file/options/option-manager.js:228:36)
    at OptionManager.init (/usr/lib/node_modules/next/node_modules/babel-core/lib/transformation/file/options/option-manager.js:373:12)
    at File.initOptions (/usr/lib/node_modules/next/node_modules/babel-core/lib/transformation/file/index.js:221:65)
    at new File (/usr/lib/node_modules/next/node_modules/babel-core/lib/transformation/file/index.js:141:24)
    at Pipeline.transform (/usr/lib/node_modules/next/node_modules/babel-core/lib/transformation/pipeline.js:46:16)
    at transpile (/usr/lib/node_modules/next/node_modules/babel-loader/index.js:38:20)
    at Object.module.exports (/usr/lib/node_modules/next/node_modules/babel-loader/index.js:131:12)
 @ multi bundles/pages/index.js

Cannot browse the application

By visiting the index page location at http://localhost/ the following thrown:

> next start

> Ready on http://localhost:3000
{ [Error: Cannot find module /home/ubuntu/workspace/.next/dist/pages/_error] code: 'ENOENT' }

Filesystem:

- package.json
- node_modules
- pages
    - index.js

index.js:

import React from 'react'

export default () => (
  <div>Welcome to next.js!</div>
)

Thanks for help!

Add typescript example

this looks awesome but I also really like TypeScript.
is there any way to integrate typescript into the workflow?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.