NextJS API route conflict - api

I have been transitioning to NextJS from CRA. I'm re-implementing authentication using SSR, and I would like to use NextJS built-in API routes to set HTTPOnly cookies.
There is a weird problem where my backend base URL is https://somesite.com/api and my frontend's - https://somesite.com/. This means that NextJS built-in API routes will be in conflict with my own backend.
I have been researching online and couldn't find any way on changing routing in NextJS, and I don't want to change base URL of my backend, since there are other services depending on it.
Has anyone had the same issue? How can I resolve this issue?

Try next.js rewrite
Rewrites allow you to map an incoming request path to a different destination path. Docs
Check Live Example here: https://stackblitz.com/edit/nextjs-rewrite
If Path is /api it'll point to JSON placeholder APIs.(ex. /api/todos)
module.exports = {
async rewrites() {
return [
{
source: '/api/:slug*',
destination: 'https://jsonplaceholder.typicode.com/:slug*'
}
];
}
};

Related

Next.js serving static files that are not included in the build or source code

I have files that are not stored in a CDN and would like to serve them with Next.js. These files are not intended to be integrated into Next.js and should not be placed in the public folder. More files will be added and I want to avoid using a custom Next.js server to do simple file serving for images that are not available during building. Additionally, this application will only be deployed locally and using a CDN is overkill for this situation.
Currently, I use Express.js and a Next.js custom server to use express.static to serve files, but this ends up slowing down Next.js and adds lots of unnecessary complexity to my stack. I'd rather just use the Next.js CLI to run my app instead of reinventing the wheel.
Is there a simple way I can serve static files within Next.js and outside the public directory?
I posted this question and my own answer here on StackOverflow because I was unable to find a good tutorial on how to do this. Nearly every google search says to use a custom server or to just put your files in the public folder, which is not what I was looking for. Hopefully, others who are looking for the same thing may find it here.
Disclaimer: I do not use Vercel to publish my applications, and I do not know if this answer will be applicable to Next.js on Vercel.
Next.js allows API routes to be customized to support Node.js HTTP handlers, which means express can also be used within Next.js API routes.
Here is some code to utilize express.static on a Next.js API route.
// pages/api/images/[name].js
// Tell Next.js to pass in Node.js HTTP
export const config = {
api: { externalResolver: true }
}
import express from 'express';
const handler = express();
const serveFiles = express.static('./path/to/files');
handler.use(['/api/images', '/images'], serveFiles);
// ^ ^
// Multiple endpoints are passed. The first one is used when visiting /api/images.
// The second one is used when visiting /images using the middleware rewrite I mention below.
// express is just a function that takes (http.IncomingMessage, http.ServerResponse),
// which Next.js supports when externalResolver is enabled.
export default handler;
However to get around visiting this endpoint via /api/images/filename, you can use Next.js's new middleware to rewrite the request!
// pages/images/_middleware.js
import { NextResponse } from 'next/server';
export function middleware(req) {
// Rewrite /images/... to /api/images/...
return NextResponse.rewrite('/api' + req.nextUrl.pathname);
}
With both these in use, visiting /images/photo.png will internally rewrite to /api/images/photo.png and in turn be handled by express.static, allowing you to serve files outside an API route and without using a custom server!
This code can surely be simplified and get rid of the need of initializing a express.js app just to handle a request, but its incredibly simple to integrate express.js into next.js without using a custom server!
I posted this question and my own answer here on StackOverflow because I was unable to find a good tutorial on how to do this. Nearly every google search says to use a custom server or to just put your files in the public folder, which is not what I was looking for. Hopefully, others who are looking for the same thing may find it here.
The public folder can only serve those files that were included at build time.
But we can do some workaround that can serve files that were not included at build time.
Solution starts here
We can create an api endpoint. For example /api/images-endpoint/[...slug].js
import fs from "fs";
import path from "path";
export default function handler(req, res) {
const imagePath = req.query.slug.join("/");
const filePath = path.resolve(".", `images-directory/${imagePath}`);
const imageBuffer = fs.readFileSync(filePath);
res.setHeader("Content-Type", "image/jpg");
return res.send(imageBuffer);
}
By this, our endpoint will read the image from the image directory and send it as a response.
Benifit/Note: This solution works for images that were added after Next project is build i-e npm run build or next build
Drawback: Using this, We can not build optimized images in Next JS Image component i-e next/image

Returned data being rendered instead of page structure in Nuxt

I'm trying to return data as JSON from the express server for a route. The data returns fine but when i open the NUXT page on the browser than the JSON data gets outputted instead of the page HTML.
Note the express route is the same as the page route. I know the routes are conflicting with each other. Do i need to have the server and front-end on different ports? Is there anything wrong i'm doing here?
Thanks
To avoid conflicts such as that you should use a prefix like /api/ or /api/v1/ something like that
In nuxt.config.js you need to define your server middleware
serverMiddleware: ["~/api/index.js"]
That file is your server. At the bottom you need to export it like this:
module.exports = {
path: "/api",
handler: app
}
Note here: app is your express app if you use express.js.
This here: const app = express();
If everything worked your root of your API should be available under host:port/api/
you cant do this if the routes for backend and frontend exactly same. this is route rules that they have to be unique and its not backend or frontend issue for e.x. you can have two routes with same url in express(api), nuxt too.
if we say the application for example is post office, the route are path to a house address (controller or action) so we can have two path to get the a house but its confusion have a same path(url or route) and different houses.
simple solutions:
as you said make the api and front separate with different ports or different domains or even have a prefix for your express routes
in express handle all of them, means return view or page with data needed instead of json data

Is there a way to redirect a NuxtJs application using Express server?

I have a NuxtJs application initialized with Express server using npx create-nuxt-app <project-name>. It is set for server-side rendering.
Express has access to NuxtJs middleware like so. ( Which comes by default when Nuxt app is created )
app.use(nuxt.render)
Now I have created a different route file in server side that handles API routes. This route works as I can access data using Axios. I have added this route right before the above code, like this. ( API routes don't work if it is added after )
app.use('/api', apiRoutes)
app.use(nuxt.render)
There is a route where, after some operation, I need to redirect the application to another page. I tried using res.redirect('/some-route'), which is an Express way for redirection but that didn't work.
Am I missing something here? Is there some other way we do redirection from server side in Nuxt application that I'm totally unaware of?
Finally found the way to redirect from the back-end.
res.writeHead(301, { Location: url })
res.end()
Here is the link to Nuxt GitHub issue comment for detailed example using server middleware.
Alternatively, you could respond with desired value to the font-end and based on the value received, you can re-direct from the front-end.

Deep linking single page application with dotNet core

I am using a dotNet core project to host an Angular2 application. I am having problems with the deep linking URLs.
For example, when I initially browse to http://localhost:54675/app/dashboard I get a 404 error because there is nothing to serve at app/dashboard. I want to actually load index.html (the angular app) and then have routing take me to app/dashboard.
I use the code below to redirect to index.html if I get a 404 and the URL has no extension.
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/index.html";
await next();
}
});
This will not work when I have a routing with parameters that include JSON such as:
http://localhost:54675/app/repairReturnListing;filter=%7B%22Status%22:[%22AWP%22]%7D
My if statement ignores requests with an extension and Path.HasExtension throws and ArgumentException on this path. The path resolves to this on the server side:
"/app/repairReturnListing;filter={\"Status\":[\"AWP\"]}"
I removed the 'HasExtension' condition and then I get a lot of console errors looking for map files that I don't host. Like this:
Failed to parse SourceMap:
http://localhost:54675/lib/js/rxjs/operator/timeout.js.map
I don't get these errors in the network tab. I think this is something used for debugging.
My angular2 app uses HTML5 routing. I use static files to serve the angular2 application. I have one webApi controller that returns some configuration data (the rest of the data is returned by another webApi project).
Waiting on a 404 and redirecting seems like a work-around and it's not even working.
Any suggestions on the best way to do this?
Check out ng2-kestrel-appserver http://tattoocoder.com/kestrel-as-a-static-server-for-angular/
Does exactly what you're looking for. It was created for RC2 but should work for the current release with few or no changes.

Using Swagger for Express alongside normal routes

I'm interested in using something like swagger-node-express to build the API for the project I'm working on. However, some parts of the app are non-api based (serving HTML instead). Has anyone got any ideas as to how I would use Swagger alongside normal routes?
You'll just need to make sure that your routes don't conflict with the Swagger routes, and your other routes will processed as usual. One easy way would be to make Swagger live under a subpath. Take a look at the docs on that score:
https://github.com/wordnik/swagger-node-express
var app = express();
var subpath = express();
app.use(express.bodyParser());
app.use("/v1", subpath);
swagger.setAppHandler(subpath);
Otherwise, you could just keep an eye out to make sure that none of the other URLs you are using in your application conflict with the Swagger URLs, and you should be able to define your routes and handlers normally. E.g. you can use Swagger to serve up docs under http://localhost:8002/api-docs.json/pet but have http://localhost:8002/foo/ do something else just by adding the route in the normal way:
app.get(/foo/, function(req, res, next) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Foo\n');
})
Using the subpath configuration is probably the cleanest approach but you could also just keep track of the routes yourself and make sure that the Swagger routes aren't conflicting with the routes in the rest of your app.