Next.js Discord

Discord Forum

Add router api issue

Answered
Checkered Giant posted this in #help-forum
Open in Discord
Checkered GiantOP
Hello, im actually trying to use the api in my project (i recently moved from page/ to app router so i got some issue) i'm using a "internationalized" thing with localhost:3000/lang/... and my middleware look like :
import { NextResponse } from "next/server";
import { match } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'

let locales = ['en', 'da','fr']
 
// Get the preferred locale, similar to the above or using a library
function getLocale(request) {
  let headers = { 'accept-language': '' }
  let languages = new Negotiator({ headers }).languages()
  let defaultLocale = 'fr'
  
  return match(languages, locales, defaultLocale) // -> 'en-US'
}
 
export function middleware(request) {
  // Check if there is any supported locale in the pathname
  const { pathname } = request.nextUrl
  const pathnameHasLocale = locales.some(
    (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
  )
 
  if (pathnameHasLocale) return
 
  const locale = getLocale(request)
  request.nextUrl.pathname = `/${locale}${pathname}`
  return NextResponse.redirect(request.nextUrl)
}
 
export const config = {
  matcher: [
    '/((?!_next).*)', 
  ],
}

But i've got some issue trying to add a register but that donst seem to work well
i call my signup api with :
const response = await fetch('/api/auth/signup', {
      method: 'POST',
      body: JSON.stringify(newUser),
      headers: {
        'Content-Type': 'application/json',
      },
});

and i have api/auth/signup/route.ts (i gave the code with the post)
but i got this : "form.tsx:53 POST http://localhost:3000/fr/api/auth/signup 404 (Not Found)"
so i guess the issue is that my middleware add the /fr to the url?
How can i fix it?

I tried by adding '/((?!api).*)' to the middleware's matcher but if i do it my styles stop working (realy weird 😅) btw i have my styles with MantineUI

Thx for your help!
Answered by Arinji
Can you try this at the top before the locale checking


Check for api in the pathname, if yes do an early return with Next response.next()
View full answer

10 Replies

Checkered GiantOP
Up
Can you try this at the top before the locale checking


Check for api in the pathname, if yes do an early return with Next response.next()
Answer
@Arinji Can you try this at the top before the locale checking Check for api in the pathname, if yes do an early return with Next response.next()
Checkered GiantOP
Ohh that could work, i’le try and i let you Know if it work
Checkered GiantOP
that work well, thank you 👍
Checkered GiantOP
Is there some thing that are not the same in page and app router for the api?
i'm trying to put my nextauth thing and i got http method error 🤔
Checkered GiantOP
ok fine
thanks!
have a nice day
@Checkered Giant that work well, thank you 👍
Mark a solution if it helped
Original message was deleted
Boop