I'm trying to follow this guide to setup testing an express API in Insomnia. I have setup a poretected route at http://localhost:5000/api/v1/private/dashboard with express-openid-connect. I have also setup an machine-to-machine application and API in auth0.
When in Insomina I try to access http://localhost:5000/api/v1/private/dashboard I am redirected to the universal login page. Trying to login does nothing. I don't think I've set this up right, but am strugging to understand the process and can't find a similar issue when searching.
I want to be able to make GET/POST/PUT/DELETE requests in Insomnia and the data be returned the same as unauthenticated routes.
I have tried various configuration changes including using client credentials, in body, using a different app type but I don't really understand auth0's configuration so don't know what I'm doing.
server.js (where the authenication check is called via oidc)
import express from "express";
import oidc from "express-openid-connect";
import publicRoutes from "./routes/publicRoutes.js";
import privateRoutes from "./routes/privateRotues.js";
const app = express();
const {
auth,
requiresAuth,
} = oidc;
const config = {
authRequired: false,
auth0Logout: true,
secret: process.env.SECRET,
baseURL: process.env.BASE_URL,
clientID: process.env.CLIENT_ID,
issuerBaseURL: process.env.ISSUER_BASE_URL,
};
console.log(config);
app.use(auth(config));
app.use("/api/v1/public", publicRoutes);
app.use("/api/v1/private", requiresAuth(), privateRoutes);
app.use("*", (req, res) => res.status(404).json({error: "File not found"}));
export default app;
Related
I am not able to load swagger for my nestJS application which is deployed on EKS.
Here is my main.ts
import {NestFactory} from '#nestjs/core';
import {NestExpressApplication} from '#nestjs/platform-express';
import {DocumentBuilder, SwaggerModule} from '#nestjs/swagger';
const swaggerUi = require('swagger-ui-express')
import {AppModule} from './app.module';
import {json, NextFunction, Request, Response} from 'express';
(async () => {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
const options = new DocumentBuilder()
.setTitle('Test')
.build();
const document = SwaggerModule.createDocument(app, options,{ ignoreGlobalPrefix: true
app.use("*/docs",swaggerUi.serve,swaggerUi.setup(document));
// Or
SwaggerModule.setup(`/docs`, app, document);
await app.listen(port, () => {
console.log(`Test service is running on port ${port}...`);
});
})
();
On my local machine the swagger doc loads correctly but when I deploy it to a development environment, it fails
dev url "https://dev-test-api.com/testservice/v1/docs/", it strips the /testservice/v1/ and redirects to "https://dev-test-api.com/docs/ and gives a 404.
I have tried couple of solutions mentioned in https://github.com/scottie1984/swagger-ui-express/issues/183
The forward-prefix option and the redirect too. None seem to work
Another problem I have is that the prefix "testservice/v1" changes as per different sandbox environments and since it is not an environment variable I don't have a way to set the path for swagger file before app is loaded.
I'm attempting to create some route guarding using the new Next.Js 12 middleware feature. My authentication is based on a JWT token set on a cookie. I had previously implemented this using the API backend on Next.Js with no issues, and still when hitting the API routes the cookie will persist on the request no problem.
My issue appears when it will request a static page from the server. No cookies are attached so I can not determine if a User is authenticated and always redirect to a log in page. So for example the request to http://localhost:3000/ (Homepage) will not send any cookies to the middleware. But, http://localhost:3000/api/user will send a cookie to the middleware. Is there a setting I have missed in the documentation to allow this to happen?
Not sure if at all helpful but here is my _middleware.ts file that sits on the root of the pages.
import type { NextFetchEvent, NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
const middleware = (req: NextRequest, ev: NextFetchEvent) => {
console.log(req.cookies);
console.log(req.cookies['user']);
console.log(req.nextUrl.pathname);
if (req.nextUrl.pathname === '/') {
return NextResponse.redirect('http://localhost:3000/login');
}
};
export default middleware;
Next.js > 12.2
req.cookies.get("user")
Before Next.js 12.2,
req.cookies?.user
I had a same problem. I use tag for routing and it works but im not sure that it is a good choice.
I'm trying to figure out how to mock calls to the auth0 authentication backend when testing a next js app with React Testing Library. I'm using auth0/nextjs-auth0 to handle authentication. My intention is to use MSW to provide mocks for all API calls.
I followed this example in the nextjs docs next.js/examples/with-msw to set up mocks for both client and server API calls. All API calls generated by the auth0/nextjs-auth0 package ( /api/auth/login , /api/auth/callback , /api/auth/logout and /api/auth/me) received mock responses.
A mock response for /api/auth/me is shown below
import { rest } from 'msw';
export const handlers = [
// /api/auth/me
rest.get(/.*\/api\/auth\/me$/, (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json({
user: { name: 'test', email: 'email#domain.com' },
}),
);
}),
];
The example setup works fine when I run the app in my browser. But when I run my test the mocks are not getting picked up.
An example test block looks like this
import React from 'react';
import {render , screen } from '#testing-library/react';
import Home from 'pages/index';
import App from 'pages/_app';
describe('Home', () => {
it('should render the loading screen', async () => {
render(<App Component={Home} />);
const loader = screen.getByTestId('loading-screen');
expect(loader).toBeInTheDocument();
});
});
I render the page inside the App component like this <App Component={Home} /> so that I will have access to the various contexts wrapping the pages.
I have spent about 2 days on this trying out various configurations and I still don't know what I might be doing wrong. Any and every help is appreciated.
This is probably resolved already for the author, but since I ran into the same issue and could not find useful documentation, this is how I solved it for end to end tests:
Overriding/configuring the API host.
The plan is to have the test runner start next.js as custom server and then having it respond to both the next.js, as API routes.
A requirements for this to work is to be able to specify the backend (host) the API is calling (via environment variables). Howerver, access to environment variables in Next.js is limited, I made this work using the publicRuntimeConfig setting in next.config.mjs. Within that file you can use runtime environment variables which then bind to the publicRuntimeConfig section of the configuration object.
/** #type {import('next').NextConfig} */
const nextConfig = {
(...)
publicRuntimeConfig: {
API_BASE_URL: process.env.API_BASE_URL,
API_BASE_PATH: process.env.API_BASE_PATH,
},
(...)
};
export default nextConfig;
Everywhere I reference the API, I use the publicRuntimeConfig to obtain these values, which gives me control over what exactly the (backend) is calling.
Allowing to control the hostname of the API at runtime allows me to change it to the local machines host and then intercept, and respond to the call with a fixture.
Configuring Playwright as the test runner.
My e2e test stack is based on Playwright, which has a playwright.config.ts file:
import type { PlaywrightTestConfig } from '#playwright/test';
const config: PlaywrightTestConfig = {
globalSetup: './playwright.setup.js',
testMatch: /.*\.e2e\.ts/,
};
export default config;
This calls another file playwright.setup.js which configures the actual tests and backend API mocks:
import {createServer} from 'http';
import {parse} from 'url';
import next from 'next';
import EndpointFixture from "./fixtures/endpoint.json";
// Config
const dev = process.env.NODE_ENV !== 'production';
const baseUrl = process?.env?.API_BASE_URL || 'localhost:3000';
// Context
const hostname = String(baseUrl.split(/:(?=\d)/)[0]).replace(/.+:\/\//, '');
const port = baseUrl.split(/:(?=\d)/)[1];
const app = next({dev, hostname, port});
const handle = app.getRequestHandler();
// Setup
export default async function playwrightSetup() {
const server = await createServer(async (request, response) => {
// Mock for a specific endpoint, responds with a fixture.
if(request.url.includes(`path/to/api/endpoint/${EndpointFixture[0].slug}`)) {
response.write(JSON.stringify(EndpointFixture[0]));
response.end();
return;
}
// Fallback for pai, notifies about missing mock.
else if(request.url.includes('path/to/api/')) {
console.log('(Backend) mock not implementeded', request.url);
return;
}
// Regular Next.js behaviour.
const parsedUrl = parse(request.url, true);
await handle(request, response, parsedUrl);
});
// Start listening on the configured port.
server.listen(port, (error) => {
console.error(error);
});
// Inject the hostname and port into the applications publicRuntimeConfig.
process.env.API_BASE_URL = `http://${hostname}:${port}`;
await app.prepare();
}
Using this kind of setup, the test runner should start a server which responds to both the routes defined by/in Next.js as well as the routes intentionally mocked (for the backend) allowing you to specify a fixture to respond with.
Final notes
Using the publicRuntimeConfig in combination with a custom Next.js servers allows you to have a relatively large amount of control about the calls that are being made on de backend, however, it does not necessarily intercept calls from the frontend, the existing frontend mocks might stil be necessary.
I'm on Nuxt 2.15.8 and trying to build an offline app with electron.js and prisma+sqlite for local DB.
In nuxt to hit a local endpoint there is a common way of using serverMiddleware and express like this:
// api.js that will be added to nuxt.config.js file as serverMiddleware
import express from 'express'
const app = express()
app.use(express.json())
export default {
path: '/api',
handler: app
}
which send endpoints beginning with api/ through app handler which I can use to access my BD (the common way to access sqlite3 DB is the same)
// added to api.js
import { PrismaClient } from '../../resources/prisma/client'
const prisma = new PrismaClient()
app.get(`/user/info`, async (req, res) => {
const result = await prisma.user.findUnique({
where: {
id: 1,
},
})
console.console.log(res);
res.json(result)
})
this will work fine on nuxt, also fine on nuxt-electron dev mode. but on built exe file serverMiddleware won't be called. So as it has be done by others (nuxt-electron accessing offline local DB) there must be a way to define endpoints on client side. any idea??
Updated:
as I changed my Nuxt-Electron boilerplate I could access serverMiddleware in exe file but it wont hit the endpoints yet!
I am trying to send POST/GET requests after using firebase serve, but this always responds in an error. I have tried many things like reinstalling node, using a backslash at the end of the url, using firebase deploy instead, resetting firebase.json, using ThunderClient in vscode instead of Postman, turning off ssl certificate for Postman, etc.
Here is my index.js file:
const functions = require("firebase-functions");
const express = require("express");
const app = express();
const Auth = require("./util/middleware");
// enable CORS
const cors = require("cors");
app.use(cors());
// can't use app level middleware :(
// app.use(Auth);
const { signup, login, logout } = require("./handlers/users");
const {
getMyBoardsOverview,
getLeaderboard,
createBoard,
} = require("./handlers/boards");
// user routes
app.post("/signup", signup);
app.post("/login", login);
app.post("/logout", Auth, logout);
// board routes
app.get("/boards", Auth, getMyBoardsOverview);
app.get("/board/:boardId/leaderboard", Auth, getLeaderboard);
app.post("/board", Auth, createBoard);
exports.api = functions.region("us-west2").https.onRequest(app);