I am trying to use matcher in my Next js middleware but documentation doesnt say much on how to implement the functionality.
All it shows is this without explaining which file it goes in or how to use the config in the middleware file:
export const config = {
matcher: '/about/:path*',
}
Does anyone have a working example of how to set up the matcher for a middleware file in Next js?
Thank you.
I was faced the same issue when learning this framework. I use nexjs v12.2.0.
to make middleware is running properly you need to put the middleware.ts or middleware.js in source directory and define the config matcher in it.
In Next.js 12.2 place a single file named middleware.ts within the root directory of your project (next to package.json):
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware (request: NextRequest) {
return NextResponse.next()
}
export const config = {
matcher: ['/api/hello/:helloId'],
}
1.Matching with config:
You have to export an object (Named export) named config from your middleware file :
middleware.js || middleware.ts
//middleware.js
export function middleware(request: NextRequest) {
return NextResponse.redirect(new URL('/about-2', request.url))
}
export const config = {
matcher: '/about/:path*',
}
2.File based Matching:
|-- pages/
│ ├── auth/
│ │ ├── index.js
│ │ └── middlware.js(1)
│ |
│ |── index.js
| |── middleware.js(2)
|__________________________
//middleware.js(1) will only run on /auth pages
//middleware.js(2) will run on all routes)
Related
I'm attempting to have a folder called 'Uploads' in my vue public folder. However, whenever I build the project using npm run build. It removes all files from the public folder and rebuilds the project deleting any additional folders added. Is there any way I can tell the vue-config.js to leave a specific folder in the public folder?
const { defineConfig } = require('#vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true
})
const path = require('path');
module.exports = {
outputDir: path.resolve(__dirname, './server/public'),
devServer:{
proxy:{
'/api':{
target:'http://localhost:8080/api/posts/'
}
}
}
};```
I have the middleware.js file within /myproject/pages/middleware.js:
export function middleware(request) {
console.log(1);
return NextResponse.redirect(new URL('/', request.url));
}
// See "Matching Paths" below to learn more
export const config = {
matcher: ['/test'],
};
Now what I expect is when i go to the page /test then it should redirect me to /. However nothing happens and I see my standard 404 page.
Any ideas why?
NextJs version: 12.2.2
Latest versions of NextJS requires user to have a single middleware on the root folder.
Instead of {root}/pages/_middleware.js, try {root}/middleware.js
For next 13.0.2 / 13.0.1
if you are using appDir: true ( experimental )
if you want to hit middleware:
put middleware.ts in root project:
( as the same hierarchy as "app" folder, not inside app folder... )
make sure tsconfig has include: [..., "middleware.ts"]
make empty "pages" folder. ( based on issue )
will hit every request:
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest ) {
console.log('lol!!!')
}
export const config = {
matcher: '/',
}
if your pages and middleware are not on the same level, then it won't work.
here is an example of middleware working with Cookies.
import { NextResponse } from "next/server";
export default function middleware(req){
let verify = req.cookies.get("loggedin");
let url = req.url
if(!verify && url.includes('/dashboard')){
return NextResponse.redirect("http://localhost:3000/");
}
if (verify && url === "http://localhost:3000/") {
return NextResponse.redirect("http://localhost:3000/dashboard");
}
}
We are in need of a solution to compile SCSS and deploy to a remote server.
We have tried using both Grunt and Gulp setups but it appears that the FTP plugins for both are no longer compatible with newer versions of Grunt/Gulp.
We have also tried WebPack today which we like, but we're not sure how to deploy the compiled files.
We are needing to do it this way as it takes too long to download a copy of a clients site, make a small style change locally and reupload. We do want the benefits of using sass therefore we need a local solution to compile our styles and then deploy them to a specified folder on the server.
Our ideal workflow would be to make a change to a scss file (JS in the near future), a background task would see the change, compile it to css and another tasks would see that and deploy it to the correct remote folder.
Any ideas?
Thanks,
Neil
A small example of how you can recompile scss to css and upload to the server via ftp
Folder structure below and the normal call to node indes.js and that's it ;)
.
├── index.js
├── output.css
├── package.json
├── style.scss
└── yarn.lock
const fs = require('fs');
const sass = require('node-sass');
const ftp = require("basic-ftp")
const pathTotheFile = './output.css';
// compile scss
sass.render({
file: __dirname + './style.scss',
outputStyle: 'compressed',
outFile: __dirname + pathTotheFile,
// sourceMap: true,
}, function (error, result) {
if (error) {
console.log(error.status);
console.log(error.column);
console.log(error.message);
console.log(error.line);
} else {
console.log(result.stats);
fs.writeFile(pathTotheFile, result.css, function (err) {
if (!err) {
uploadCSStoServer();
}
})
}
});
// copy file to server
async function uploadCSStoServer() {
const client = new ftp.Client()
client.ftp.verbose = true
try {
await client.access({
host: "myftpserver.com",
user: "very",
password: "password",
secure: true
})
console.log(await client.list())
await client.uploadFrom("README.md", "README_FTP.md")
// await client.downloadTo("README_COPY.md", "README_FTP.md")
}
catch (err) {
console.log(err)
}
client.close()
}
Any file in Meteor private directory app not work. ex:
myapp/
client/
server/
main.js
imports/
vnc.js
private/
bin/
x11vnc <-----
public/
in /server/main.js
import '/imports/vnc.js'
in /imports/vnc.js
import { Meteor } from 'meteor/meteor'
Meteor.startup(() => {
x11vncExecutavel = Assets.absoluteFilePath('bin/x11vnc');
})
the error is Error: Unknown asset: bin/x11vnc
https://docs.meteor.com/api/assets.html
Meteor version is 1.4.3.1
I'm hosting a site using firebase and want to be able to prevent people from accessing it, tried using a .htaccess file, wondering if anyone has been able to do it before.
Here is a little hack that simulates HTTP Basic authentication using firebase cloud functions and a little rearrangement of files.
There are 3 steps to this:
Set up the necessary cloud function
Move the files you want to protect into a "secret" folder
Update your firebase.json
1. Cloud Function
const USERNAME = 'USERNAME'
const PASSWORD = 'PASSWORD'
const denyAccess = (res) => {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="Authorization
Required');
res.end('Unauthorized');
}
exports.authorizeAccess = functions.https.onRequest((req, res) => {
if (typeof req.headers.authorization !== 'string') {
denyAccess(res);
return;
}
const base64Auth = req.headers.authorization.split(' ')[1];
if (typeof base64Auth !== 'string' ) {
denyAccess(res);
return;
}
const [user, pass] = Buffer.from(base64Auth,
'base64').toString().split(':');
if (user !== USERNAME || pass !== PASSWORD) {
denyAccess(res);
return;
}
const urlObject = url.parse(req.url);
urlObject.pathname =
`/${PASSWORD}${urlObject.pathname}`;
const location = url.format(urlObject);
res.writeHead(302, { location });
res.end();
});
2. Move files into secret folder
Suppose the folder that you have set as public in firebase.json looks like this:
.
├── index.html
├── js
| ├── main.js
| └── main.js.map
└── styles.css
then make it look like this
.
└── PASSWORD
├── index.html
├── js
| ├── main.js
| └── main.js.map
└── styles.css
3. firebase.json
{
...
"rewrites": {
"source": "/"
"function": "authorizeAccess"
}
...
}
We had to password protect our source maps in production; we had to have them in there in the first place so that Sentry would pick it up. Our build scripts would take care of moving the files into the necessary folder.
If you are hosting a site, and want to access firebase data on your site, you can add authentication to your application to control who can change or view data. According to the manual: Firebase Authentication
With Firebase hosting channels you can have "preview" channels that include a random hash in their URLs, like SITE_ID--CHANNEL_ID-RANDOM_HASH.web.app. So that only people you gave this secret URL can access this site. Note that "preview" channels have an expiration delay that can be up to 30 days from the date of deploy.