The React Framework

Overview

Next.js

Getting Started

Visit https://nextjs.org/learn to get started with Next.js.

Documentation

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

Who is using Next.js?

Next.js is used by the world's leading companies. Check out the Next.js Showcase to learn more.

Community

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

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

Our Code of Conduct applies to all Next.js community channels.

Contributing

Please see our contributing.md.

Authors

Comments
  • Warning: Prop className did not match.

    Warning: Prop className did not match.

    Examples bug report

    Example name

    with-styled-components

    Describe the bug

    Also posted here: #2538

    Using css prop introduced with styled-components v4 causes Warning: Prop className did not match..

    To Reproduce

    Add any HTML element with css prop.

    Expected behavior

    Correctly styled rendering on the server side without any warnings.

    Screenshots

    57497472-7b657c00-72e0-11e9-84c5-e7e5fa0d351c

    System information

    • OS: Windows
    • Chrome
    • Version of Next.js: 8.1.0

    Additional context

    Here is an example I created to demonstrate the issue: https://codesandbox.io/embed/jlwvwyy0ow

    Open this and refresh once the building is done: https://jlwvwyy0ow.sse.codesandbox.io/

    good first issue type: needs investigation 
    opened by th0th 273
  • Static Generation / SSG Improvements

    Static Generation / SSG Improvements

    Summary

    Allow Next.js to become fully hybrid by providing methods to do both static generation and server-side rendering on a per-page basis.

    • Two new per-page data fetching methods
      • getStaticProps - Opt-in to static generation (SSG) at next build time.
      • getServerSideProps - Opt-in to server-side rendering (SSR) which renders on-demand.
    • A new method for statically generating (SSG) a set of routes from dynamic sources
      • getStaticPaths - Return list of parameters for dynamic routes to do static generation (SSG)

    This RFC exclusively discusses API additions. All new functionality is completely backwards compatible and can be incrementally adopted. This RFC introduces no deprecations.

    Background

    When building websites or web applications you generally have to choose between 2 strategies: Static generation (SSG) or server-side rendering (SSR).

    Next.js instead lets you build hybrid applications that allow you to choose per-page which strategy is used. Starting with Next.js 9, pages without getInitialProps get statically optimized and output as .html files upon next build.

    However, you might want to do data fetching while generating static pages for your specific use case.

    For example, to statically generate marketing pages from a CMS or a blog section of the site.

    Using getInitialProps would opt you into SSR in that case.

    Next.js currently has a next export command, that makes the application fully SSG, losing the hybrid nature of Next.js.

    If you use next export with getInitialProps there is another problem that surfaces. getInitialProps is called at build time (which is great), but then when you use next/link to move between pages getInitialProps is called client-side, instead of using the next export result.

    This also means the data source (CMS / API endpoint) is called directly on client-side transitions, if your data source is down, client-side transitions break while moving between pages.

    We've collaborated with heavy users of SSG and next export in Next.js like HashiCorp (thanks @jescalan) and extensively investigated the right constraints for introducing two new data fetching methods: getStaticProps and getServerSideProps. But also a way to provide parameters to statically generate static pages for dynamic routes: getStaticPaths (replacement for exportPathMap that is per-page).

    These new methods have many advantages over the getInitialProps model as there is a clear distinction between what will become SSG vs SSR.

    • getStaticProps marks the page to be statically generated at build time (when running next build)
    • getStaticPaths allows for returning a list of parameters to generate at build time for dynamic routes
    • getServerSideProps marks the page to be server-side rendered on every request and is the most similar to the current getInitialProps behavior when using a server.

    Separating these methods also allows us to provide the correct context object that can be typed using TypeScript. When you opt for a specific rendering strategy you get the correct values, currently with getInitialProps you have to guess what is available on SSG vs SSR when using TypeScript.

    Furthermore, by making these methods explicit, it'll allow us to document the different trade-offs more clearly.

    Implementation

    Note that all these methods are top-level on the page component file and can't be nested, similar to getInitialProps.

    getStaticProps

    Using getStaticProps means the page will be rendered statically at build time (SSG).

    This new method will allow you to do data fetching for a page that will be statically generated into a .html file at next build time.

    Next.js will also automatically generate a JSON file that holds the result of getStaticProps at next build time. This is being used for client-side routing.

    When client-side routing through next/link or next/router, Next.js will fetch this JSON file to get the props needed to render the page client-side.

    Properties are returned under a props key so that other options can be introduced in the future.

    // pages/index.js
    
    // getStaticProps is only called server-side
    // In theory you could do direct database queries
    export async function getStaticProps(context) {
      return {
        // Unlike `getInitialProps` the props are returned under a props key
        // The reasoning behind this is that there's potentially more options
        // that will be introduced in the future.
        // For example to allow you to further control behavior per-page.
        props: {}
      };
    }
    

    The context will contain:

    • params - The parameters when on a dynamic route.

    getStaticPaths

    This is an extension on getStaticProps usage for dynamic routes.

    getStaticPaths replaces the need for having a exportPathMap and works per-page.

    Since you might want to statically generate a list of urls that have a dynamic parameter, like in the example below a slug. Next.js will provide a getStaticPaths method that allows for returning a list of urls. Since it's a async method you can also fetch that list from a data source like your CMS.

    // pages/blog/[slug].js
    
    // `getStaticProps` gets a `params` object holding the dynamic parameters
    // For `/blog/hello-world` it would look like `{ slug: 'hello-world }`
    export async function getStaticProps({ params }) {
      return {
        props: {}
      };
    }
    
    // `getStaticPaths` allows the user to return a list of parameters to
    // render to HTML at build time.
    export async function getStaticPaths() {
      return {
        paths: [
          // This renders /blog/hello-world to HTML at build time
          { params: { slug: "hello-world" } }
        ]
      };
    }
    

    Fallback

    In many cases you might not want to pre-render every possible route in your application at build-time (for example if you have millions of products). For this reason Next.js will automatically generate a fallback page that is a render of the page without data (so that a loading state can be shown) for when the page hasn’t been generated yet.

    The exact behavior of serving will be:

    • Incoming request
      • Next.js checks if the path was generated at build time
        • If the path was generated
          • serve directly
        • If the path was not generated
          • Serve the fallback
            • Next.js renders the page (with data) in the background and adds it to the list of generated pages
            • Subsequent request to the same path will serve the generated page
            • This ensures that users always have a fast experience and never have slow TTFB from server-rendering while preserving fast builds and static-generation properties

    In case you want paths that weren’t generated at build time to result in a 404 that is also possible by returning fallback: false from getStaticPaths

    // `getStaticPaths` allows the user to return a list of parameters to
    // render to HTML at build time.
    export async function getStaticPaths() {
      return {
        // Opt-out of the described fallback behavior
        fallback: false,
        paths: [
          // This renders /blog/hello-world to HTML at build time
          { params: { slug: "hello-world" } }
        ]
      };
    }
    

    getServerSideProps

    When using getServerSideProps, the page is not statically generated (SSG) and instead renders on-demand on every request to the server (SSR).

    Next.js will also automatically expose an API endpoint that returns the result of calling getServerSideProps. This is being used for client-side routing.

    When client-side routing through next/link or next/router, Next.js will fetch this exposed API endpoint to get the JSON data that is turned into the props needed to render the page client-side.

    This method is the most similar to the current getInitialProps, with the main difference being getServerSideProps is always executed server-side instead of in the browser. Either on server-side rendering or the API fetch when client-side routing.

    Similarly to getStaticProps the properties are returned under a props key.

    // pages/index.js
    
    // getServerSideProps is only called server-side
    // In theory you could do direct database queries
    export async function getServerSideProps(context) {
      return {
        // Unlike `getInitialProps` the props are returned under a props key
        // The reasoning behind this is that there's potentially more options
        // that will be introduced in the future.
        // For example to allow you to further control behavior per-page.
        props: {}
      };
    }
    

    The context will contain:

    • params - The parameters on a dynamic route
    • req - The HTTP request object
    • res - The HTTP response object
    • query - The query string (not entirely sure about this one, but probably needed)

    Authored by @timneutkens, @Timer, @ijjk, @lfades. Collaborated with @rauchg, @jescalan and others 🚀

    opened by timneutkens 250
  • Add login / authentication example

    Add login / authentication example

    With:

    • re-usable authentication helper across pages
    • session synchronization among tabs
    • simple passwordless email backend hosted on now.sh

    I think this will be hugely helpful to a lot of newcomers.

    opened by rauchg 209
  • Next.js API routes (and pages) should support reading files

    Next.js API routes (and pages) should support reading files

    Feature request

    Is your feature request related to a problem? Please describe.

    It's currently not possible to read files from API routes or pages.

    Describe the solution you'd like

    I want to be able to call fs.readFile with a __dirname path and have it "just work".

    This should work in Development and Production mode.

    Describe alternatives you've considered

    This may need to integrate with @zeit/webpack-asset-relocator-loader in some capacity. This plugin handles these types of requires.

    However, it's not a necessity. I'd be OK with something that only works with __dirname and __filename (no relative or cwd-based paths).

    Additional context

    Example:

    // pages/api/test.js
    import fs from 'fs'
    import path from 'path'
    
    export default (req, res) => {
      const fileContent = fs.readFileSync(
        path.join(__dirname, '..', '..', 'package.json'), 
        'utf8'
      )
      // ...
    }
    

    Note: I know you can cheat the above example ☝️ with require, but that's not the point. 😄

    kind: story area: standalone mode 
    opened by Timer 146
  • Next 9.5.1 out of memory after some hot reloads

    Next 9.5.1 out of memory after some hot reloads

    Bug report

    Describe the bug

    Since updating to 9.5.x (from 9.4.x), i get an out of memory error after 10 something hot reloads:

    FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

    it did rarely happen in 9.4.1, but it happens very consistantly in 9.5.x

    To Reproduce

    thats probably tricky. it happens on big projects and might be related to some bug in the hot reload / rebuild. Maybe it happens when there are some import circles?

    Expected behavior

    nextjs should not go out-of-memory

    System information

    • OS:macOS
    • Browser: chrome
    • Version of Next.js: 9.5.1
    • Version of Node.js: 12.13.1

    Additional information

    we are using a custom server with typescript

    please add a complete reproduction 
    opened by macrozone 144
  • Top-level app component and animated route transitions

    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.

    opened by dlindenkreuz 135
  • Build error next.js 6.0.0

    Build error next.js 6.0.0

    I just upgraded to [email protected], I use a custom server, when I try to run dev, I get an error.

    npm run dev
    
    > [email protected] dev /Users/foo/gitlab/next-project/backend
    > babel-node ./src/server.js
    
    /Users/foo/gitlab/next-project/backend/node_modules/babel-core/lib/transformation/file/options/option-manager.js:328
            throw e;
            ^
    
    Error: Plugin 0 specified in "/Users/foo/gitlab/next-project/backend/node_modules/next/babel.js" provided an invalid property of "default" (While processing preset: "/Users/foo/gitlab/next-project/backend/node_modules/next/babel.js")
        at Plugin.init (/Users/foo/gitlab/next-project/backend/node_modules/babel-core/lib/transformation/plugin.js:131:13)
        at Function.normalisePlugin (/Users/foo/gitlab/next-project/backend/node_modules/babel-core/lib/transformation/file/options/option-manager.js:152:12)
        at /Users/foo/gitlab/next-project/backend/node_modules/babel-core/lib/transformation/file/options/option-manager.js:184:30
        at Array.map (<anonymous>)
        at Function.normalisePlugins (/Users/foo/gitlab/next-project/backend/node_modules/babel-core/lib/transformation/file/options/option-manager.js:158:20)
        at OptionManager.mergeOptions (/Users/foo/gitlab/next-project/backend/node_modules/babel-core/lib/transformation/file/options/option-manager.js:234:36)
        at /Users/foo/gitlab/next-project/backend/node_modules/babel-core/lib/transformation/file/options/option-manager.js:265:14
        at /Users/foo/gitlab/next-project/backend/node_modules/babel-core/lib/transformation/file/options/option-manager.js:323:22
        at Array.map (<anonymous>)
        at OptionManager.resolvePresets (/Users/foo/gitlab/next-project/backend/node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! [email protected] dev: `babel-node ./src/server.js`
    npm ERR! Exit status 1
    npm ERR! 
    npm ERR! Failed at the [email protected] dev script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
    
    npm ERR! A complete log of this run can be found in:
    npm ERR!     /Users/foo/.npm/_logs/2018-04-30T08_41_09_819Z-debug.log
    

    UPDATE all this passed after upgrading all babel packages to v7

    Now this is the new error.... See below for complete error message

    ERROR  Failed to compile with 1 errors                                                                                                                                                                                               10:32:07
    
     error  in ./pages/_document.js
    
    Module build failed: Error: [BABEL] /Users/foo/gitlab/zyombo/backend/pages/_document.js: .value is not a valid Plugin property
    
    opened by paschaldev 125
  • trailing slash in link for legit page works for client side navigation but leads to not found bundle and 404 on hard refresh (ssr)

    trailing slash in link for legit page works for client side navigation but leads to not found bundle and 404 on hard refresh (ssr)

    trailing slash in link for legit page works for client side navigation but leads to not found bundle and 404 on hard refresh (ssr)

    Bug report

    Describe the bug

    let me know if title needs further clarification.

    all relevant issues has been closed with reasoning that its been fixed in 6-canary (I believe it is not) or by improved serve (which is true only in perhaps production static export).

    I'm rewriting my existing blog to next.js and i previously used trailing slashes. Latest serve can help with it once i build my next.js powered blog. But in order to fix dev env i need either to get rid of trailing slashes and utilize 301 Moved Permanently in prod; or live with broken trailing slash support in dev.

    To Reproduce

    Here is minimal reproducible case (link to repro repo is below snippet):

    // pages/index.js
    import Link from "next/link";
    
    export default () => (
      <Link href="/about/">
        <a>About</a>
      </Link>
    );
    
    // pages/index.js
    export default () => "about";
    

    Minimal reproducible repo https://github.com/iamstarkov/next.js-trailing-slash-bug-demo

    1. clone repo git clone https://github.com/iamstarkov/next.js-trailing-slash-bug-demo
    2. change directory cd next.js-trailing-slash-bug-demo
    3. install deps yarn
    4. run dev: yarn dev
    5. open http://localhost:3000/
    6. open devtools' network tab
    7. observe http://localhost:3000/_next/static/development/pages/about.js being 200ed
    8. observe http://localhost:3000/_next/on-demand-entries-ping?page=/about/ being 200ed
    9. observe http://localhost:3000/about/ being 404ed
    10. observe persistent attempts to resolve http://localhost:3000/about/
    11. observe in the terminal Client pings, but there's no entry for page: /about/
    12. refresh the page
    13. observe 404 page.
    14. remove trailing slash in the url or click http://localhost:3000/about
    15. observe page being 200ed
    16. to ensure error persistence repeat steps 5-15 once.

    Expected behavior

    1. /about/ shouldnt be resolved as 404 not found
    2. /about/ should be resolved as 200 ok
    3. Server should not print Client pings, but there's no entry for page: /about/
    4. both /about and /about/ should work the same way

    Screenshots

    N/A

    System information

    • OS: macOS High Sierra 10.13.6 (17G65)
    • Browser (should not matter, but can repro'ed in chrome 69.0.3497.100 and safari Version 12.0 (13606.2.11) (was the same for safari 11)
    • Version of Next.js: 7.0.0 (could repro on 5.x and 6.x)

    Additional context

    Add any other context about the problem here.

    If you change this code in https://github.com/zeit/next.js/blob/459c1c13d054b37442126889077b7056269eeb35/server/on-demand-entry-handler.js#L242-L249

    or node_modules/next/dist/server/on-demand-entry-handler.js locally

              const { query } = parse(req.url, true)
              const page = normalizePage(query.page)
    +         console.log('query.page', query.page);
    +         console.log('page', page);
    +         console.log('Object.keys(entries)', Object.keys(entries));
              const entryInfo = entries[page]
    
              // If there's no entry.
              // Then it seems like an weird issue.
              if (!entryInfo) {
                const message = `Client pings, but there's no entry for page: ${page}`
    

    and restart next dev and open http://localhost:3000/ and click about link then:

    • for /about
      query.page /about
      page /about
      Object.keys(entries) [ '/', '/about' ]
      
    • for /about/:
      query.page /about/
      page /about/
      Object.keys(entries) [ '/', '/about' ]
      Client pings, but there's no entry for page: /about/
      

    I think the problem (at least part of it) is in inability of onDemandEntryHandler's middleware to find page in entries if page has trailing slash.

    I hope my 2 hours of investigation and preparation can help with fixing this issue.

    kind: story 
    opened by iamstarkov 124
  • Custom Cache-Control response header for `/_next/image`

    Custom Cache-Control response header for `/_next/image`

    Bug report

    Describe the bug

    When requesting /_next/image(.*), I'm getting this Response header:

    Cache-Control: public, max-age=60
    

    And it's fine... What's not fine is that I'm getting the same exact Response headers even when I use custom headers in next.config.js, i.e.:

    module.exports = {
      async headers() {
        return [
          {
            // This works, and returns appropriate Response headers:
            source: '/(.*).jpg',
            headers: [
              {
                key: 'Cache-Control',
                value:
                  'public, max-age=180, s-maxage=180, stale-while-revalidate=180',
              },
            ],
          },
          {
            // This doesn't work for 'Cache-Control' key (works for others though):
            source: '/_next/image(.*)',
            headers: [
              {
                key: 'Cache-Control',
                // Instead of this value:
                value: 'public, max-age=180, s-maxage=180, stale-while-revalidate=180',
                // Cache-Control response header is `public, max-age=60` in production
                // and `public, max-age=0, must-revalidate` in development
              },
            ],
          },
        ]
      },
    }
    
    

    To Reproduce

    Try this next.config.js above, with an image that uses common <img> tag like this:

    <img src="/YOUR_IMAGE_IN_PUBLIC_FOLDER.jpg">
    

    And another tag that uses the new next/image component, with the same or whatever image url, for example:

    <Image src="/YOUR_IMAGE_IN_PUBLIC_FOLDER.jpg">
    

    And try requesting those images in the browser, and look into Devtools -> Network tab, the Response headers, and see that for common <img> tag it's actually changed, whereas for new <Image> component it is not.

    Expected behavior

    For /_next/image(.*) urls, I expected to see Headers that I setup, i.e. Cache-Control: public, max-age=180, s-maxage=180, stale-while-revalidate=180.

    Screenshots

    Common <img>:

    image

    New <Image>:

    image

    System information

    • OS: not applicable / any
    • Browser (if applies): not applicable / any
    • Version of Next.js: 10.0.3
    • Version of Node.js: 12.18.0
    • Deployment: both next start on development machine, and actual Vercel deployment (screenshots demonstrate the case with local machine, but I've confirmed that the same is happening on a Vercel deployment)

    Additional context

    Originally I created an issue using "Feature request" template, and it got translated into "Idea discussion": https://github.com/vercel/next.js/discussions/19896 (how to delete/close it pls? doesn't seem to be possible), - initially I wasn't sure if it's even possible to setup custom headers, and how that supposed to work, though I just needed that functionality. But later, upon discovering that there's such a functionality already, I figured out that actually /_next/image overrides both custom headers in next.config.js and headers property of Vercel config, i.e. it's not just some idea of a feature that is "not implemented", but it's actual bug.

    kind: story 
    opened by jerrygreen 113
  • Add support to transpile modules inside node_modules

    Add support to transpile modules inside node_modules

    Now some of us ships NPM packages (specially components) written in ES2015 without transpiling them.

    That's a pretty good thing specially if they are gonna used in a project like Next.js or CRA (which does transpiling). They offer benefits like:

    • No need to transpile before shipping to NPM
    • Get the benefit of Webpack 2's tree-shaking

    But we can't do this now we exclude everything inside node_modules from babel transpiling.

    So, here's the proposed solution.

    We have an entry in next.config.js to include modules which needs to go through babel. See:

    module.exports = {
       transpileModules: [
         "my-component",
         "redux/src"
       ]
    }
    
    kind: story area: Compiler 
    opened by arunoda 113
  • Allow next/head to render react components

    Allow next/head to render react components

    ℹ️ There is an easy "workaround" you can apply instead of using React components, which are NOT supported within next/head as of NextJS 10.2

    Fixes: #17721 Fixes: #17842

    Essentially, >=9.5.4 breaks compatibility for having react components within Head. While it's true that NextJS never truly supported this...

    title, meta or any other elements (e.g. script) need to be contained as direct children of the Head element, or wrapped into maximum one level of <React.Fragment> or arrays—otherwise the tags won't be correctly picked up on client-side navigations.

    ...this is a fundamental React principle and we should support the concept of component composition. For example,

    const HomePage = () => (
        <>
            <Head>
                <CustomTitle />
                <ThirdPartyScripts />
            </Head>
            <div>Homepage</div>
        </>
    )
    

    I tracked the issue to https://github.com/vercel/next.js/pull/16758/files#diff-f0591f99e1e66f02b12d5f64977b579eR86 where apparently we serialize head data in the window object now: window.__NEXT_DATA__, which doesn't handle components. I'm not sure the best way to handle that, but I created logic in head-manager.ts to handle react components and their potential children.

    TODO

    • [x] Allow custom components in Head to not throw runtime errors (initial render/page load)
    • [ ] Allow custom components in Head to render on client navigation
    • [x] Update Tests
      • [x] Ensure component children aren't duplicated (only rendered once)
      • [ ] Ensure component children aren't orphaned 🤔
    area: documentation type: next 
    opened by jflayhart 107
  • Page with `experimental-edge` runtime and a `basePath` is deployed on Node instead of Edge when using Vercel

    Page with `experimental-edge` runtime and a `basePath` is deployed on Node instead of Edge when using Vercel

    Verify canary release

    • [X] I verified that the issue exists in the latest Next.js canary release

    Provide environment information

    Operating System:
      Platform: darwin
      Arch: x64
      Version: Darwin Kernel Version 21.6.0: Mon Aug 22 20:17:10 PDT 2022; root:xnu-8020.140.49~2/RELEASE_X86_64
    Binaries:
      Node: 16.16.0
      npm: 8.14.0
      Yarn: 1.22.17
      pnpm: 7.9.5
    Relevant packages:
      next: 13.1.1-canary.1
      eslint-config-next: N/A
      react: 18.2.0
      react-dom: 18.2.0
    

    Which area(s) of Next.js are affected? (leave empty if unsure)

    Middleware / Edge (API routes, runtime)

    Link to the code that reproduces this issue

    https://github.com/remorses/repro-edge-basepath-next

    To Reproduce

    • Deploy the project to Vercel
    • Visit the deployed url (with /docs path, for example at https://repro-edge-basepath-next.vercel.app/docs)
    • Notice that the function crash with ReferenceError: self is not defined
    • The function is deployed with Node instead of Edge runtime

    Describe the Bug

    Next projects using edge runtime and base path get a runtime error on Vercel ReferenceError: self is not defined

    The cause of this bug is that Vercel incorrectly tries to run the edge runtime page on Node (where self is not defined)

    Expected Behavior

    Vercel should deploy with edge function and not Node

    Which browser are you using? (if relevant)

    No response

    How are you deploying your application? (if relevant)

    Vercel

    template: bug 
    opened by remorses 0
  • @next/font font-weight not working correctly in Chrome

    @next/font font-weight not working correctly in Chrome

    Verify canary release

    • [x] I verified that the issue exists in the latest Next.js canary release

    Provide environment information

    Operating System: Platform: darwin Arch: x64 Version: Darwin Kernel Version 21.4.0: Fri Mar 18 00:46:32 PDT 2022; root:xnu-8020.101.4~15/RELEASE_ARM64_T6000 Binaries: Node: 14.19.0 npm: 6.14.16 Yarn: 1.22.17 pnpm: 7.13.2 Relevant packages: next: 13.1.1 eslint-config-next: 13.1.1 react: 18.2.0 react-dom: 18.2.0

    Which area(s) of Next.js are affected? (leave empty if unsure)

    Font optimization (@next/font)

    Link to the code that reproduces this issue

    https://github.com/denvradiy/next-fonts-loading-issue

    To Reproduce

    Hard refresh (shift + command+ R) the page multiple times in Chrome in host and font-weight will crash.

    Describe the Bug

    If you refresh the page with reseting the cache (shift + command+ R) multiple times in Chrome then font-weight crashes and displays incorrectly.

    This bug appears only on host (in this case it's vercel). But if I run next build and next start locally on my computer then it works correctly.

    For testing purposes I took generated create-next-app example and didn't change anything

    https://github.com/denvradiy/next-fonts-loading-issue - repo to reproduce https://next-fonts-loading-issue.vercel.app/ - vercel https://monosnap.com/file/2uyrSIIo3k4pMpKW0H9RV1JUB4WY9m - screen recording

    Expected Behavior

    Font weight should work correctly in all modern browsers

    Which browser are you using? (if relevant)

    Chrome

    How are you deploying your application? (if relevant)

    Vercel

    template: bug 
    opened by denvradiy 1
  • Using special symbols (such as long arrows) with `next/font`

    Using special symbols (such as long arrows) with `next/font`

    Describe the feature you'd like to request

    My website uses sideways arrows and long arrows as icons for links (see https://www.mikeheddes.nl) but when I use next/font to load the Inter font the arrows are rendered using the fallback fonts. I would like a way to specify that I also want some special symbols to be included in the font. Note that even if I leave the subsets unspecified the arrows are not rendered properly while I assumed that without subsets specified it would include all the characters the font supports (which includes the sideways arrows).

    Describe the solution you'd like

    Either support for more character subsets such that the subset that includes the arrows can be specified; or something similar to the text parameter in the google fonts API (see below).

    Describe alternatives you've considered

    Right now I use Google fonts where I specify the text parameter like so: https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap&text=⟵⟶

    template: story 
    opened by mikeheddes 0
  • node:16-alpine no longer works

    node:16-alpine no longer works

    Verify canary release

    • [ ] I verified that the issue exists in the latest Next.js canary release

    Provide environment information

    There were updates on node:16-alpine image and example Dockerfile doesn't work anymore. It works now with node:16-alpine3.16

    Which example does this report relate to?

    with-docker

    What browser are you using? (if relevant)

    No response

    How are you deploying your application? (if relevant)

    No response

    Describe the Bug

    In https://github.com/vercel/next.js/blob/canary/examples/with-docker/Dockerfile node:16-alpine should be changed to node:16-alpine3.16 Otherwise it gives error:

    container_linux.go:380: starting container process caused: exec: "/bin/sh": stat /bin/sh: no such file or directory
    

    Here are commits that caused this issue: https://github.com/nodejs/docker-node/commits/2a15356c778b366621aa370a4294c59ac1df9c6a/16/alpine3.17/Dockerfile

    Expected Behavior

    Docker file should build

    To Reproduce

    Build with-docker example as is

    area: examples 
    opened by PiotrJozefow 0
  • (AppDir) There's currently no way to run code before the UI is interactive.

    (AppDir) There's currently no way to run code before the UI is interactive.

    Describe the feature you'd like to request

    I'm working on the French government design system React library compatible with AppDir but I'm having difficulties since I can't find a way to run code ASAP.

    In PageDir it wat possible to do:

    // pages/_app.tsx
    import App from "next/app";
    import { startServer, startClient } from "@codegouvfr/react-dsfr";
    
    export const isBrowser = typeof window === "object" && typeof document === "object";
    
    if( isBrowser ){
        startClient();
    }else{
        startServer();
    }
    
    export default App;
    

    In this configuration startClient() was executed ASAP on the browser and everything was fine.

    Now in AppDir the only way I found to get a bit of code running on both the client and the server is the following:

    // app/StartDsfr.tsx
    "use client";
    
    import { startServer, startClient } from "@codegouvfr/react-dsfr";
    
    export const isBrowser = typeof window === "object" && typeof document === "object";
    
    if( isBrowser ){
        startClient();
    }else{
        startServer();
    }
    
    export default function StartDsfr(){
        return null;
    }
    
    // app/layout.tsx
    
    import StartDsfr from "./StartDsfr";
    
    export default function RootLayout({ children }: { children: React.ReactNode; }) {
    
      return (
        <html suppressHydrationWarning={true}>
          <head>
              <StartDsfr />
          </head>
          <body>
            {children}
          </body>
        </html>
      );
    
    }
    

    This really feels like a hack and startClient() is executed too late, startClient is responsible for setting the dark mode so it results in a white flash for dark mode users.

    https://user-images.githubusercontent.com/6702424/209474952-bab2a037-efe6-461c-9995-35357e41a908.mov

    Describe the solution you'd like

    // app/layout.tsx
    +import { runAsap } from "next/integration";
     import { startServer, startClient } from "@codegouvfr/react-dsfr";
    
    +runAsap(isBrowser => {
    +
    +    if( isBrowser ){
    +        startClient();
    +    }else{
    +        startServer();
    +    }
    +
    +});
    
    export default function RootLayout({ children }: { children: React.ReactNode; }) {
    
      return (
        <html suppressHydrationWarning={true}>
          <head>
              <StartDsfr />
          </head>
          <body>
            {children}
          </body>
        </html>
      );
    

    Describe alternatives you've considered

    Using