NextAuth
For notes on using nextauth library with Next.JS see NextAuth .
NextJS 13 API Routes
Create a route.tsx
file inside your apps
directory at the subdirectory you want to address
You must export a function for each HTTP method you want to serve e.g. GET
, POST
and so on.
import { NextRequest, NextResponse } from 'next/server' ;
type ResponseData = {
message : string
}
export async function GET ( req : NextRequest ) {
//res.status(200).json({ message: 'Hello from Next.js!' })
return new NextResponse ( JSON . stringify ({ message: "hello world" }), { status: 200 });
}
SearchParams
NextJS calls queryParams searchParams. It provides ways of accessing them in different scenarios:
Client Side
clientside hook useSearchParams()
Server Side Pages
Passing them into a page
function:
export default async function Preview ({
params ,
searchParams ,
} : {
params : Record < string , string >;
searchParams ?: { [ key : string ] : string | string [] | undefined };
}) {
// function body
}
Server Side API Endpoints
export async function GET (
req : NextRequest ,
{ params } : { params : Params }
) : Promise < NextResponse > {
const { searchParams } = new URL (req.url);
/// function body...
}
Dynamic Routes
We can use square brackets in the folder segment name to indicate a path param that will be filled e.g. [slug]
as per the documentation
These params are then passed to the method as per the api routes documentation :
export async function GET (
request : Request ,
{ params } : { params : { slug : string } }
) {
const slug = params.slug // 'a', 'b', or 'c'
}
WebPack
In some cases we might want to specifically skip backend packages when the frontend package is being built. We can use nextjs config with the webpack ignore plugin to skip certain things.
The following snippet is based-on an updated version of this answer
/** @type {import('next').NextConfig} */
const nextConfig = {
webpack : ( config , { isServer , webpack }) => {
// Ignore bee-queue
if ( ! isServer){
config.plugins. push ( new webpack. IgnorePlugin ({ resourceRegExp: / ^ (bee-queue) $ / }));
config.plugins. push (
new webpack. IgnorePlugin ({
checkResource ( resource , context ) {
// If I am including something from my backend directory,
// I am sure that this shouldn't be included in my frontend bundle
if (resource. includes ( '/backend/' ) && ! context. includes ( 'node_modules' )) {
return true ;
}
return false ;
},
}),
);
}
return config;
}
};
export default nextConfig;
Prisma