-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
_middleware.js
example without Next.js
#50
Comments
_middlware.js
example without nextjs_middleware.js
example without nextjs
Hey! We’re working on adding some examples for this. Middleware does indeed work with any framework, or just vanilla HTML, by placing the _middleware file in your root directly (or for framework authors, using the File System API). |
_middleware.js
example without nextjs_middleware.js
example without Next.js
Am I correct in assuming this is unlikely to be addressed until 1Q 2022 due to the upcoming year-end holidays? Just curious. TIA for any such info. |
Any news on this topic? |
For anyone trying to use
function rewrite(destination) {
return new Response(null, {
headers: {
'x-middleware-rewrite':
typeof destination === 'string'
? destination
: destination.toString(),
},
})
}
|
@remorses Although this doesn't eliminate the need for non-Next documentation from Vercel, it nonetheless is interesting and useful. Thanks! |
We're still working on it - apologies for the delay. |
@remorses Just as a starter for those of us not all that into Next 😄 , how would you adjust the following import type { NextRequest } from 'next/server'
export function middleware(req: NextRequest) {
// You can add and append headers in multiple ways,
// below we'll explore some common patterns
// 1. Add a header to the `Headers` interface
// https://developer.mozilla.org/en-US/docs/Web/API/Headers
const headers = new Headers({ 'x-custom-1': 'value-1' })
headers.set('x-custom-2', 'value-2')
// 2. Add existing headers to a new `Response`
const res = new Response(null, { headers })
// 3. Add a header to an existing response
res.headers.set('x-custom-3', 'value-3')
// 4. Merge existing headers with new ones in a response
return new Response(
'Open the network tab in devtools to see the response headers',
{
headers: {
...Object.fromEntries(res.headers),
'x-custom-4': 'value-4',
},
}
)
} |
Instead of NextRequest you have to use Request, which is a javascript built in To migrate to a simple request, you can see how |
@brycewray Would be great if you can share your code once implemented! |
Any update on documentation for non-nextjs projects? All the above is helpful, but something a bit more formal would be much appreciated. |
I'm always getting an error like:
If I try to put The only way to bypass the error is moving The code of the middleware is something like this: "use strict";
const middleware = {
default: function (request) {
return new Response("hi from the edge!");
},
};
_ENTRIES = typeof _ENTRIES === "undefined" ? {} : _ENTRIES;
_ENTRIES["middleware_pages/_middleware"] = {
default: async function (ev) {
const result = await middleware.default(ev.request, ev);
return {
promise: Promise.resolve(),
waitUntil: Promise.resolve(),
response:
result ||
new Response(null, {
headers: {
"x-middleware-next": 1,
},
}),
};
},
}; I've also added a Any quick pointer, @leerob ? Thanks. |
Alright, looks like it works when using Now my problem is... |
Really would appreciate seeing some official docs detailing how to build middleware for a non-Next.js app. Managed to get a basic middleware working adapting @brycewray's snippet above to not use Next.js imports and saving this in my repo as
|
A bit of progress in the last half an hour from digging around in
You can do rewrites in a similar fashion, using a One major issue I'm currently having is that if you write a blank middleware such as below, the middleware successfully runs and your app is 'served', however any assets ( Another thing I'm having issues with is that even though Vercel's middleware are run through ESBuild, I cannot seem to use any ES6 functionality and have to write much more primitive JS. I can't use things such as I've managed to convert the basic-auth-password middleware and get it sort of working despite the above, but I hit the issue with CSS/JS assets throwing 404s meaning I can't take it any further at the mo. My demo can be found here and the code for the
|
For anyone interested, I've made an example on how to deploy to Vercel Edge without Next.js: https://github.com/frandiox/hydrogen-vercel-edge As mentioned before, the key was using |
Nice! (But requires Shopify, right? I think what most of us are seeking are examples that require no specific platform but, rather, are as vanilla as possible.) |
Thanks @frandiox, nice example using the File System API - that raises a good point that there are really two parts to this issue, I think what we need in this repo is an example of both:
It seems like the second point is supported in Vercel, but perhaps not fully working/documented yet. As @brycewray mentions, I think this is what most people would be seeking so that the overhead of setting up Vercel middleware for a non-Nextjs project is as simple as possible. |
I see you mentioned Hydrogen - what other frameworks are y'all wanting to use Middleware with? P.S. I'm still following along here 😄 |
Can’t answer for others, @leerob, but I just want as plain-vanilla JS as possible, for converting an existing CF Worker to work on Vercel. Since Edge already uses CF Workers, seems it wouldn’t be that hard, although I readily confess that I’m only guessing about that. |
@leerob I'm using docusaurus, so I think that means static HTML. |
I'm encountering the following error on deployment with a
|
@edcrampin could you share the repo you have for converting the basic password auth? That would be a great example to work from. I'm having trouble understanding the various roots in the project, i.e., where the middleware should go. |
HELP! WE NEED DOCUMENTATION. ffs..... |
With the understanding that there may not be bandwidth at Vercel to reproduce all the examples in non-Next form, maybe @leerob et al. could take just one of the simpler examples — such as add-header or geolocation — and produce a non-Next form of it. It would be like a Rosetta Stone, showing that “Thing A gets done in Next projects like this (existing example) but in plain-vanilla JS it gets done like this (proposed example).” That could be really helpful and, perhaps, wouldn’t take too much time to convert from whichever Next project you select. Just a thought. 🙂 |
@brycewray agreed, I've been planning to raise a PR to add something like this for a few basic examples using both the file system API and potentially also fully vanilla (single middleware file?) but struggling to get the time to look at this for now. The main nuisance to work around is how to organise middleware examples in this repo, and then also re-working the plop scripts to support this new structure. I'd propose
...and moving all existing examples to the |
@edcrampin That all sounds great! It’ll be tremendously appreciated — but I humbly re-suggest :) that, in the meantime and in view of the team’s absolutely understandable time limitations, the starting effort be something utterly simple, quick, and dirty, even if it’s only a vanilla version of |
@brycewray sounds completely sensible - I'll see what I can do. |
@brycewray here's an example of an These mostly work but I'm coming across the same issue as I mentioned previously where certain assets return a 404 which I believe to be a bug within Vercel somewhere as certain assets load fine whilst others don't. Here's an example from the |
@edcrampin Thanks very much! Will stand by for @leerob to weigh in on your question before trying. |
Thanks for the example, @edcrampin ! I feel that I've been able to rule out issues with the _middleware file and package.json thanks to that repo. However, there appears to be some remaining issue, and I don't understand where to start analyzing this issue. It appears that moving the _middleware file will switch this error between being a simple middleware and a filesystem API issue, but there's something that the edge function deployer just doesn't like about ...something? My repo? My framework? My account? As an aside, it would be nice to be able to test these things without waiting for a remote deployment and committing. I'd love to hear input on what could be related to this issue, and I'm interested in helping to make sure that the documentation can help people who are using whatever new technology, and want to add middleware.
|
I'm also using the latest docusaurus and getting the same error I tried with a noop middleware and it still fails, most probably related to docusaurus: export default function middleware(req: Request) {
return new Response(null, {
headers: {
"x-middleware-next": "1",
},
});
} |
@edcrampin , could you share more about the settings you're using to deploy your example? I assumed that it would use either the Other or Create React App preset, with the root directory I've tried deploying it and it failed:
|
Btw, I got the following response from Vercel support:
So I guess we just have to be patient :) |
I feel like you guys putting examples of middleware implementations on your site, saying you work with all frameworks, only to not, is blatantly false advertising. Nowhere on these pages does it say that middleware is only supported by Next.js apps. https://vercel.com/features/edge-functions https://vercel.com/docs/concepts/functions/edge-functions Riiiiiiiight...... |
Forgot to swing back here, but with the stable release of Middleware, it can now be used with all frameworks 😄 Will be adding more examples, as well! This is just the start. https://vercel.com/docs/concepts/functions/edge-middleware/quickstart |
Vercel Middleware stabilized (vercel/examples#50 (comment)), re-add the password protection for staging environments. See 7728506. This reverts commit 8f01e6e.
I did finally get it working on a Hugo repo: While most of its headers-handling could’ve been done in @leerob, my compliments to your team for the content of both the Edge Functions and Middleware sections in the documentation — the info is much more comprehensive, and considerably easier to follow, than the last time I checked. |
@david-morris @charlax did you ever get your docusaurus sites behind authentication? |
@dmarkbreiter yes, I think we just crammed Docusaurus behind a Next.js shim before this was fixed though. |
Is there a |
Here is my middleware for a docusaurus static site: const auth = process.env.AUTH
export default function middleware(request) {
const basicAuth = request.headers.get('Authorization')
if (!basicAuth) {
return new Response('Access denied', {
status: 401,
headers: { 'WWW-Authenticate': 'Basic' },
})
}
const authValue = basicAuth.split(' ')[1]
if (authValue !== auth) {
return new Response('Access denied', {
status: 401,
headers: { 'WWW-Authenticate': 'Basic' },
})
}
} Use echo -n "username:password" | base64 to generate the |
Since this is still the easiest resource to find for using Vercel middleware without Next, here's a tip I wish I had known earlier. @vercel/edge gives you import { rewrite } from "@vercel/edge"
export const config = {
matcher: "/((?!api|static).*)",
}
export default function middleware(_request: Request) {
return rewrite("/404")
} |
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
The text was updated successfully, but these errors were encountered: