I've created a middleware for authentication on my nuxt application, and I want to call it inside a layout.
Problem is, I'm calling it like this:
export default {
middleware: 'auth',
and it is returning me the following warning:
callback-based asyncData, fetch or middleware calls are deprecated. Please switch to promises or async/await syntax
I'm new into the front-end world and I searched but couldn't find/understand how to implement this async/await syntax on my middleware call. Can you help me?
Thanks in advance.
Faced a similar problem. I also use middleware: ['lang'], I got such an error and for a long time could not understand why this happened, if I did not change anything in the code. It turned out that in lang.js I mistakenly receive the second argument req
export default async function ({ isHMR, app, store }, req) {
}
Only a function servermiddleware can take multiple arguments
module.exports = function (req, res, next) {
Related
I have a test API under: pages\api\accounts\login.js. And I am learning the new app folder, which is still an experimental feature in Next.js (as of today).
Is it possible to move my login script into the app folder? I tried moving/renaming to app\api\accounts\login\pages.js, but when I do this:
async function handler(req, res) {
console.log(res);
}
export default handler;
I use the URL: http://localhost:3000/api/accounts/login. I get:
Server Error
Error: Cannot find module for page: /api/accounts/login
I also tried moving it to: app/api/accounts/login/page.js. But I get the same error.
As you can read on the API Routes page of the new documentation of Next.js, API routes are currently as before, meaning they should be in the pages/api folder:
API routes should still be defined in the pages/api/* directory and not moved to the app directory.
We are considering what API routes would look like in the app directory and will update this page in the future.
Some use cases where an API route was used to keep access tokens secure when calling an external API from the client can now be done directly in Server Components.
Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a route.
For example, the following API route pages/api/user.ts returns a json response with a status code of 200:
// pages/api/user.ts
import { NextApiRequest, NextApiResponse } from 'next'
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ name: 'John Doe' })
}
How can I use a middleware ONLY FOR my json-server specific routes? In the json-server docs, I can see the following instructions:
const jsonServerRouter = jsonServer.router('mock-server/db.json')
server.use(customMiddleware)
server.use(jsonServerRouter) // customMiddleware should be executed ONLY FOR this jsonServerRouter
/*
Problem is here, customMiddleware has already been executed,
so following routes will use the middleware too
*/
server.use(otherRoutes)
What I've tried:
// This syntax is similar to the previous code. So it doesnt work
server.use(customMiddleware, jsonServerRouter)
// Passing the middleware to the 'router' function doesnt work
const jsonServerRouter = jsonServer.router('mock-server/db.json', customMiddleware)
Somewhat new, please bear with me. Trying to use passport to authenticate only specific routes in a website. The routes are in a separate file called blog_a.js. I have the following functions created in the main server.js file:
function checkAuthenticated(req, res, next) {
if (req.isAuthenticated()){
return next()
}
res.redirect('/login')
}
function checkNotAuthenticated(req, res, next) {
if (req.isAuthenticated()){
return res.redirect('/')
}
next()
}
However, I'm trying to pass the above functions into the blog_a.js module, so I can use them as middleware to protect the routes within that module.
I have tried to use module.exports = {checkAuthenticated, checkNotAuthenticated} at the bottom of the main 'server.js' file, and then use a let server = require('../server.js') line to import these functions to the module that contains the routes I want to protect.
However, the above server variable comes back as undefined, and I've tried several permutations / destructuring methods to try to import it. All to no avail, I keep getting the routes failing due to the "undefined" object--Error: Route.get() requires a callback function but got a [object Undefined].
How can I set up the authentication in the server.js file but then pass its authentication functions to be used as middleware within an individual route file?
I looked at this solution, but it doesn't clearly explain how to get the middleware functions from one module--server.js--to another module--blog_a.js.
I got the following response on Patreon from Kyle of Web Dev Simplified, and it worked like a charm!
"You should be able to just create another file that is called authMiddleware.js or something like that. Then in that file define and export the functions at the end (module.exports = { function1, function2 }). Now in the places you need those functions you should be able to import them like so (const { function1, function2 } = require('./authMiddleware'))."
So I followed Kyle's advice and created the following separate file authMiddleware.js:
function checkAuthenticated(req, res, next) {
if (req.isAuthenticated()){
return next()
}
res.redirect('/login')
}
function checkNotAuthenticated(req, res, next) {
if (req.isAuthenticated()){
return res.redirect('/')
}
next()
}
module.exports = { checkAuthenticated, checkNotAuthenticated }
... and then used the following require statements to get access to the functions:
-in main server.js --> const {checkAuthenticated, checkNotAuthenticated} = require('./authMiddleware.js')
-in router file blog_a.js --> const {checkAuthenticated, checkNotAuthenticated} = require('../authMiddleware.js')
Thanks!
Can anyone help here. I am really frustrated with how the mockImplementation works.
So, first of all I am using jest for node testing. I am using the commonjs modules. what I wanna do is that I am trying to mock a module using mockImplementation() and change its implementation between different tests according to this documentation here: https://jestjs.io/docs/en/es6-class-mocks#replacing-the-mock-using-mockimplementation-docs-en-mock-function-api-mockfnmockimplementationfn-or-mockimplementationonce-docs-en-mock-function-api-mockfnmockimplementationoncefn.
My code look like this:
const exportBigQueryTableModule =require('../repository/exportBigQueryTable')
jest.mock('../repository/exportBigQueryTable')
describe('deleting files on table export fail', () => {
mockExportBigQueryTable = jest
.fn(() => Promise.resolve())
.mockResolvedValueOnce()
.mockRejectedValueOnce(new Error('Could not export table'))
exportBigQueryTableModule.mockImplementation(mockExportBigQueryTable)
it(' should do some test', () => {})
})
The problem here is that looks like that this line jest.mock('../repository/exportBigQueryTable') create for me a default mock kind of jest.fn() and the module is always loaded with that default function. So the mock function that I did provide on the test using the mockImplementation never overrides the previous one, I do not get what is the problem here. Why the same exmaple on the official documentation works the only difference is that it uses es6 modules on the doc sample.
I am not sure if I am missing something here.
As we know, Express is not very good in handling async functions, in particular for the error handling.
I did define an asyncMiddleware as follows:
const asyncMiddleware = fn => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
And then:
router.get('/', asyncMiddleware(myRouteHandler))
Is there a way to properly rewrite the middleware in order to make it usable directly by the Express router?
router.use(asyncMiddleware)
Koa supports promises natively, it's expected that Express 5 will do this as well.
Is there a way to properly rewrite the middleware in order to make it usable directly by the Express router?
There is no way. In order to do that, Express app and router (express.Router and express.Route classes) methods that use middlewares and route handlers should be monkey-patched to do what asyncMiddleware does.
Otherwise promise-based middlewares should be manually wrapped with a helper like asyncMiddleware.