vercel / examples Goto Github PK
View Code? Open in Web Editor NEWEnjoy our curated collection of examples and solutions. Use these patterns to build your own robust and scalable applications.
License: MIT License
Enjoy our curated collection of examples and solutions. Use these patterns to build your own robust and scalable applications.
License: MIT License
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
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
});
Searching for an example, I'm getting an extra item:
Example: "API Rate Limit"
Another item, example: "tweet"
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.
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.
It could be something simple as just showing cursors and being able to write or paint something, or more complicated as a video game.
Here are some open source tools that could be used to build it (because real time is hard, we shouldn't build it ourselves)
Next.js Live uses Replicache for its realtime capabilities, although it's not open source, the other ones are completely free to use.
Ember starter template at https://vercel.com/templates cannot be deployed.
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
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
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?
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?
The example was added in: #20
It doesn't have a deployment yet.
While trying to use this example, and following the steps on optimize, it does not recognize my Analytics tag
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
Errors:
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
type-check
script to pipeline and to ui
and app
skipLibcheck
to tsconfig/nextjs.json
ui
to only use tsc --noEmit
for typecheckingui
and update its package.json
to match basic exampleIgnore Build Command
on Vercel once [email protected] ships w/--dry=json
Website: https://authzed.com/blog/user-defined-roles/
Some useful links:
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?
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
return res.status(201).json(Item);
Returns undefined
even on a successful insert
Query params filter has infinite redirection loop
Edge function folder: https://github.com/vercel/examples/tree/main/edge-functions/query-params-filter
Bug:
Loading URL from readme - https://edge-functions-query-params-filter.vercel.sh/?a=b&allowed=test leads to an infinite redirection loop
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.
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?
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.
Example: https://github.com/vercel/examples/tree/main/edge-functions/bot-protection-botd
When running the bot check the, middleware reports an error and does not perform a check:
Botd failed with: { [TypeError: fetch failed]
cause: [TypeError: define_process_default.nextTick is not a function] }
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:
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: ''
}
A clone of vice.com would be great.
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:
fs
and other core modules are not available (e.g. process
, util
, os
, buffer
, et al.)Hi, can you point me to the server-side analytics example?
Thanks in advance
The edge-function example using i18n is not using the normal Internationalized Routing but rather a custom file route-based approach.
Will edge functions support "proper" i18n? If so, is there a timeline?
I'm evaluating if it's worth rewriting everything using this EF approach and essentially moving all of the pages/*
to pages/[locale]/*
.
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?
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.
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
Not much to say here. It'd be nice to have a Build Output API example of using Edge Middleware to rewrite the URL, including the query string.
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
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.
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.
After running npm i & npm run dev, it throws
../../node_modules/@vercel/examples-ui/anchor/anchor.module.css
Error: Cannot find module '@acme\design-system\tailwind'
Read information from #42 and return it so we can use it in other places.
Place that code inside packages/meta
Hi, I'm testing this example but the result is the default values (see image)
I used my local environment and the option to deploy using vercel.com (https://geolocation-beta.vercel.app/)
Is there any configuration required to make it work?
Add the following information to each README.md in examples:
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.
Just click the Deploy
button on the README page.
And make sure the READMEs are updated too with code snippets e.g. https://github.com/vercel/examples/tree/main/edge-functions/json-response
The clone and deploy section of the readme for the Personalization Builder IO example contains a URL that points to a different example.
See: https://github.com/vercel/examples/tree/main/edge-functions/personalization-builder-io#clone-and-deploy
I'm looking for the python example from https://vercel.com/docs/runtimes, which I can git clone
and run the code
This example, seems to be no longer recommended, because of this PR, vercel/next.js#33410.
Is there any way to still enforce the rewriting behavior?
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.
Unhandled Runtime Error
Error: The provided as
value (/) is incompatible with the href
value (/_sites/[site]). Read more: https://nextjs.org/docs/messages/incompatible-href-as
https://github.com/vercel/examples/tree/main/edge-functions/hostname-rewrites
I just cloned this repo and tried to run it on my local and I am facing this error:
How to solve it. I haven't found any solution!
Thank in advance
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.