Giter Site home page Giter Site logo

vercel / examples Goto Github PK

View Code? Open in Web Editor NEW
3.2K 82.0 975.0 40.02 MB

Enjoy our curated collection of examples and solutions. Use these patterns to build your own robust and scalable applications.

License: MIT License

Shell 0.01% TypeScript 69.99% JavaScript 22.09% CSS 2.90% HTML 1.86% Rust 0.03% Python 0.55% Vue 0.53% Svelte 0.95% SCSS 1.09%
examples vercel nextjs

examples's Introduction

Vercel Examples

Enjoy our curated collection of examples and solutions. Use these patterns to build your own robust and scalable applications. We're going to be shipping new examples weekly. Stay tuned!

  • Edge Functions – Build high-performance APIs that are deployed to every Edge Network region. Learn more.
  • Edge Middleware – Provide speed and personalization to your users. Learn more.
  • Solutions – Demos, Architectures, and Best Practices
  • Starter – Fully functional applications that encompass an idea as a robust starting point.

Vercel Templates

Multiple examples are being featured in Vercel's Templates, visit that page for more advanced filtering options.

For Vercelians

Examples that have front matter metadata will create a new Draft template in Contentful, for more steps on how to publish a template, read Publishing Templates.

Adding a new example

To quickly start contributing with a new example, run the following commands:

pnpm i
pnpm new-example

If the script above isn't used, make sure the example complies with the following:

Adding a template

If you would like the example to be featured in vercel.com/templates then also add the front matter metadata to the top of the readme, like in bot-protection-datadome. To know all the possible values for each metadata take a look at internal/fields.json.

If you want to add related templates to your template, copy the slug from the other template into the relatedTemplates field, for example for vercel.com/templates/next.js/monorepo-turborepo the slug is monorepo-turborepo, as written in solutions/monorepo/README.md

The pre-commit hook

We use Husky to manage the pre-commit Git hook in this repo. Husky configures hooks automatically during install, so you don't need to do anything special to get them working, but if it fails to install, you can run the following command to install it manually:

pnpm run prepare

Code changes automatically go through Prettier and ESLint when you make a commit, please do not skip these steps unless they're broken and in that case let us known by creating an issue.

Read the Docs

If you have any questions or suggestions about the docs, feel free to open a discussion, or submit a PR with your suggestions!

Provide Feedback

  • Start a Discussion with a question, piece of feedback, or idea you want to share with the team.
  • Open an Issue if you believe you've encountered a bug that you want to flag for the team.

examples's People

Contributors

cramforce avatar delbaoliveira avatar dependabot[bot] avatar dferber90 avatar domeccleston avatar dominiksipowicz avatar dummdidumm avatar endangeredmassa avatar github-actions[bot] avatar goncy avatar guibibeau avatar ijjk avatar jaredpalmer avatar javivelasco avatar joe-statsig avatar leerob avatar leggetter avatar lfades avatar lpalmes avatar manovotny avatar miraan avatar nuta avatar okbel avatar simpsoka avatar speediing avatar stephdietz avatar steven-tey avatar styfle avatar tknickman avatar tootallnate 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

examples's Issues

Custom error page with hostname-rewrites / i18n

Both examples rewrite the path to prefix some data, but it doesn't seem to work for error pages (both 404.js and _error.js). Is there any way around this without custom handling in getServerSideProps?

write EPROTO in geolocation example

I created app with the command

npx create-next-app --example https://github.com/vercel/examples/tree/main/edge-functions/geolocation <my_project_name>

Then start it with npm run dev in the my_project_name directory

When I hit the localhost:3000, I see the error in console

error - Error: write EPROTO 281473417277456:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:../deps/openssl/openssl/ssl/record/ssl3_record.c:332:

node version: v16.13.2
npm version: 8.1.2

Update turborepo example w/ latest techniques

  • Add type-check script to pipeline and to ui and app
  • Add skipLibcheck to tsconfig/nextjs.json
  • Tweak ui to only use tsc --noEmit for typechecking
  • Remove dev mode from ui and update its package.json to match basic example
  • Leverage new Ignore Build Command on Vercel once [email protected] ships w/--dry=json

Update UI

Let's make sure this points to this repo and all clone and deploy buttons work

CleanShot 2021-10-25 at 16 20 55@2x

jwt-authentication example

When I try to run the example locally, I get:

error - node_modules/jose/dist/browser/jws/flattened/sign.js (11:0) @ new FlattenedSign
TypeError: payload must be an instance of Uint8Array
null

Oddly enough, when I deploy it everything seems to work fine. Any Ideas how that happens? I checked, both vercel and my local machine are on node 14.18.1

'logging' example is not provided; no pattern provided

Hello,

The https://nextjs.org/docs/middleware#examples page suggests that there are number of examples of various types in this repo

Authentication
Bot protection
Redirects and rewrites
Handling unsupported browsers
Feature flags and A/B tests
Server-side analytics
Advanced i18n routing requirements
Logging

all point to the same resource:

https://github.com/vercel/examples/tree/main/edge-functions

Keying in on Logging, searching the Readme for the string oggi yields no match. Similarly ack through the repo for /oggi/i and you will only find a mention in feature-flag-configcat/ example. Furthermore, this is logging from a client function not from a server function e.g. the middleware function.

Absent any directions, I ahem, duplicated this error vercel/next.js#13214

Further research at https://nextjs.org/docs/api-reference/edge-runtime#unsupported-apis, a leap whose connection was made my reading URL paths, suggests this is not possible. OK, I can live with that, but then it becomes all the more important that it be documented how to log server-side data in the middlewares.

I suspect most people are implementing a custom server to get 'fs' access, a practice that seems discouraged in the docs.

So is there either:

  1. An example of doing server-side logging in the Next Middleware (if not...)
  2. The expectation that that should be possible and, if so, how will that be possible if fs and other core modules are not available (e.g. process, util, os, buffer, et al.)

Prop href did not match. Server & Client

@lfades

Developed Custom middleware based on cookies

Passing data from one page to another page using router.push.When accessing using useRouter() in another page.

Getting below message in browser console

Prop href did not match. Server: "/second#" Client: "/second?id=45&
name=sai&buildingName=ss&no=&street=555555#"

Below code of middleware function

import { NextResponse } from 'next/server';

function middleware(request) {
  const cookie = request.cookies.token;
  const { pathname } = request.nextUrl;
  if (
    cookie === undefined &&
    ['/first','/second'].includes(pathname)
  ) {
    return NextResponse.redirect('/login');
  }


  if (
    cookie !== undefined &&
    ['/sample' ].includes(pathname)
  ) {
  return NextResponse.next();
}
return NextResponse.next();
}


export default middleware;


How fix above issue?

i18n geo usage with next-i18next & Next's built in internationalized routing

I'm trying to follow the example within the i18n folder but am running into some issues since my requirements are a bit different.

How our use case differs from the example:

  • We still want to use next-i18next and store our translations in JSON files.
  • We want to use different paths for different locales like the behavior is when using Next's built-in Internationalized Routing, i.e. when user is visiting from Iceland, we want to have all of his visiting pathnames prefixed with /is.

Here's the code for the middleware I'm currently working with:

import { NextRequest, NextResponse } from "next/server";

const PUBLIC_FILE = /\.(.*)$/;
const SUPPORTED_LOCALES = ["en", "is", "pt"];
const DEFAULT_LOCALE = "en";

export function middleware(req: NextRequest) {
  const currentPathName = req.nextUrl.pathname;

  // 1. Only rewrite files that don't have a file extension (favicon, etc)
  // 2. We don't want to detect locale if the user is already visiting with a locale prefix.
  if (!PUBLIC_FILE.test(currentPathName)) {
    let country = req.geo?.country?.toLowerCase();
    if (!country && process.env.NODE_ENV === "development") {
      country = "is";
    }

    const isVisitingWithLocalePath =
      !!SUPPORTED_LOCALES.find((l) => currentPathName.includes(l)) ||
      currentPathName === `/${country}`;

    const locale =
      req.headers.get("accept-language")?.split(",")?.[0] || DEFAULT_LOCALE;
    const newLocale = country || locale;

    if (!isVisitingWithLocalePath) {
      req.nextUrl.locale = newLocale;
      req.nextUrl.pathname = `/${newLocale}`;
    } else {
      req.nextUrl.locale =
        currentPathName === `/${country}`
          ? DEFAULT_LOCALE
          : currentPathName.split("/")[1];
    }

    return NextResponse.rewrite(req.nextUrl).cookie("NEXT_LOCALE", newLocale);
  }
}

When visiting our page we receive the following error:

Error: The provided `as` value (/) is incompatible with the `href` value (/[company]).

If I add console.log(req.nextUrl) just before returning, this is the output (running locally):

NextURL {
  href: '/is/is',
  origin: '',
  protocol: '',
  username: '',
  password: '',
  host: '',
  hostname: '',
  port: '',
  pathname: '/is',
  search: '',
  searchParams: URLSearchParams {},
  hash: ''
}

edge function geo is not working (undefined values)

Middleware in my api folder.

import { NextResponse } from "next/server";

export async function middleware(req) {
  const { nextUrl: url, geo } = req;

  console.log(url);
  console.log(geo);

  if (url.pathname === "/api/ip-info") {
    const country = geo.country || "";
    const region = geo.region || "";

    url.searchParams.set("countryCode", country);
    url.searchParams.set("region", region);

    return NextResponse.rewrite(url);
  }

  return NextResponse.next();
}

Logs from Vercel.

/api/ip-info

{ city: undefined,
  country: undefined,
  region: undefined,
  latitude: undefined,
  longitude: undefined }

What am I missing?

The request is triggered via the CookieConsent consentTypeRequired function.

    <>
      <Head>
        <meta
          name="viewport"
          content="minimum-scale=1, initial-scale=1, maximum-scale=5, width=device-width, shrink-to-fit=no, viewport-fit=cover"
        />
      </Head>
      <DefaultSeo {...SEO} />
      <CookieConsentProvider consentTypeRequired={consentTypeRequired}>
        <Component {...pageProps} />
        <CookieConsent />
      </CookieConsentProvider>
    </>

Is there anything I could simplify? Currently I have a fallback in the ip-info api that uses external services to determine the geo. However that causes initial delays.

Cannot deploy "Basic Auth Password Protection" example to Vercel

Problem

I copied and pasted the _middleware.ts from example repo to my Next project, everything worked fine on development environment, and I can run yarn build successfully. When trying to deploy to Vercel, I kept getting an error said An unexpected internal error occurred, then the deploy got failed. The error happened right after Uploading build outputs....

I found the official example will meet the error, too. We cannot even deploy the official example to Vercel.

How to re-produce the issue

Just click the Deploy button on the README page.

CleanShot 2021-11-04 at 18 27 28

CleanShot 2021-11-04 at 18 34 47

Hostname Rewrite

Hi,

When we rewrite the url from the top level middleware, the to [site]/page.jsx , the main logic will work from page.jssx
However, if we have a second level of middleware at /[site]/[level2]/page.jsx with a middleware at /[site]/[level2]/_middleware.js.
The second middledware will not run because we are rewriting the url.

Is there any way to make the second middleware work?
Thank You

TypeError in jwt auth example

The jwt-authentication throws this error and doesn't start.

error - node_modules\jose\dist\browser\jws\flattened\sign.js (11:0) @ new FlattenedSign
TypeError: payload must be an instance of Uint8Array

I also opened a discussion on the jose repo because the issue happens also when implementing the code in my repo.

Deploy aws-dynamodb get error: Could not load credentials from any providers

CredentialsProviderError: Could not load credentials from any providers

const client = new DynamoDBClient({
  accessKeyId: process.env.ACCESS_KEY,
  secretAccessKey: process.env.SECRET_KEY,
  region: process.env.REGION
});

should edit to:

const client = new DynamoDBClient({
  credentials: {
    accessKeyId: process.env.ACCESS_KEY,
    secretAccessKey: process.env.SECRET_KEY
  },
  region: process.env.REGION
});

`_middleware.js` example without Next.js

Is there an example of using _middlware.js wihout Nextjs?

My use case is to use _middlware.js as a reverse proxy, the problem of using nextjs is that _middlware.js won't reroute anything with path starting with /_next

A/B Testing with Google Optimize project does not recognize Analytics

While trying to use this example, and following the steps on optimize, it does not recognize my Analytics tag

image
The image says that "We found problems with the Optimize installation on this page" and something like the "Google Analytics tracking code not found".

I also noticed that in the code at components/layout.ts there is a commented part which is

<Page>
      {/* <Script
      src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_TRACKING_ID}`}
      onLoad={() => {
        window.dataLayer = window.dataLayer || []
        function gtag() {
          dataLayer.push(arguments)
        }

        gtag('js', new Date())
        gtag('config', process.env.NEXT_PUBLIC_GOOGLE_TRACKING_ID)
      }}
    /> */}
      <Script
        src={`https://www.googleoptimize.com/optimize.js?id=${process.env.NEXT_PUBLIC_OPTIMIZE_CONTAINER_ID}`}
      />
      <GaProvider value={ga}>{children}</GaProvider>
</Page>

but if I uncomment it

image

Errors:

  • line 30: Property 'dataLayer' does not exist on type 'Window & typeof globalThis'.ts(2339)
  • line 32: Cannot find name 'dataLayer'.ts(2304)
  • lines 35 and 36: Expected 0 arguments, but got 2.ts(2554)

So I wanted to know how I should include Google Analytics along with Google Optimize in this example.

Oh, and I included both IDs on my .env.local

Same item showing up multiple times on main page

Searching for an example, I'm getting an extra item:

Example: "API Rate Limit"

image

Another item, example: "tweet"

image

And so on...

I couldn't find where this list is being rendered to try to detect the problem, but inspecting with the react dev tools I noticed that only the "tweet" item is present.

image

On Chrome Version 99.0.4844.51 (Official Build) (64-bit) - Ubuntu 20.04 LTS

Not sure if this is the correct place to report the issue. Please let me know.

edge functions/feature-flag-optimizely not loading variations/sort flag

It's possible I'm misunderstanding how this demo is supposed to work (https://github.com/vercel/examples/tree/main/edge-functions/feature-flag-optimizely), but when I go to the application I see products sorted alphabetically. When I go in and delete optimizely_visitor_id cookie and reload the page I don't see any changes. I tried deleting the cookie and reloading a few times, but did not notice any changes.

How am I supposed to trigger a new variation of the feature flag?

Missing an example for using waitUntil() for metrics

I'm trying to set up datadog tracing in my NextJS app. It seems like this should be possible with middleware, but I'm not finding an example for this.

The docs say: An example of why you would use waitUntil() is integrations with logging tools such as [Sentry](https://sentry.io/) or [DataDog](https://www.datadoghq.com/). After the response has been sent, you can send logs of response times, errors, API call durations or overall performance metrics.

But I'm not finding a way of executing code in the middleware after the response has been returned to the caller, and I'm finding several folks confused by similar use cases:

Can we get an example of this?

Add contribution docs

We need to talk about all the things to do before adding a new example, like using the UI package, adding the demo URL, and other things that might be important and can help us when doing PR reviews

Is it possible to get query paramaters with useRouter() when rewriting with _middleware.ts ?

When rewriting through next.config.js as explained here https://nextjs.org/docs/api-reference/next.config.js/rewrites it was possible to get query parameters from useRouter().query but when using rewrites via _middleware.ts with NextResponse.rewrite(path) as shown in this example https://github.com/vercel/examples/blob/main/edge-functions/hostname-rewrites/pages/_middleware.ts useRouter().query is an empty object.

Or is the only way to access paramters from context.params using getStaticProps or getServerSideProps ?

Thanks.

Edit : Seems related to #55 , when I export getStaticProps or getServerSideProps, even without returning context.params useRouter().query is populated but if not I got the error described there and an empty object.

Microfrontends example: Missing package version blocks the app build

The project can't be build or start because the apps in the apps folder lack necessary dependencies, which are not installed on yarn install because of some missing package data.

yarn create next-app --example https://github.com/vercel/examples/tree/main/solutions/microfrontends microfrontends
> yarn install

yarn install v1.22.18
warning Missing version in workspace at "/srv/apps/my/microfrontends/apps/docs", ignoring.
warning Missing version in workspace at "/srv/apps/my/microfrontends/apps/main", ignoring.
> yarn build

docs:build: $ next build
main:build: $ next build
docs:build: /bin/sh: 1: next: not found
main:build: /bin/sh: 1: next: not found
docs:build: error Command failed with exit code 127.
docs:build: info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
main:build: error Command failed with exit code 127.
main:build: info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
main:build: ERROR: command finished with error: command (apps/main) yarn run build exited (127)
command (apps/main) yarn run build exited (127)

PR provided #363

I can have multiple custom domains using host-rewrites, correct?

Just want to make sure. There is an emphasis on sub-domains in the docs and example. And I do see multiple custom domains. But there is a single root domain in the .env file, and I don't really want a root domain, I just want multiple root/main/host names that are related, but different.

Cannot use import statement outside a module

When running the cdk example the following error occurs when running cdk bootstrap:

import 'source-map-support/register';
^^^^^^

SyntaxError: Cannot use import statement outside a module

JWT Auth example

when implementing the jwt auth example in my app i get the following in the verce dev logs: 'eval' not allowed in Middleware pages/_middleware

This does not seem to happen with the example itself but the error message is not particularly clear about what is causing the issue. Any pointers?

Cors example: TypeError: Cannot read properties of undefined (reading 'set')

I have added the cors.ts file to our project and added the middleware function to use cors, however when I run yarn dev I the following error

TypeError: Cannot read properties of undefined (reading 'set')

The error comes from the cors function inside cors.ts. We have not modified the code.

We are on NextJS 12.1.0. Any help here is apprecaited.

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.