Nextjs dynamic routes in Amplify

Viewed 381

I have the following directory structure in my Nextjs app:

pages/post/[id]/index.js

I am trying to configure Amplify to correctly route this URL:

mydomain.com/post/123

I have the following rewrite configured:

{
    "source": "/post/<*>",
    "target": "/post/[id]/index.html",
    "status": "200",
    "condition": null
},

But it isn't working. What is the correct format for the Amplify rewrite when the directory is a dynamic route?

My routes do work when running locally. I can't get it configured in Amplify.

2 Answers

If you want to have mydomain.com/post/123 work, then your directory needs to match this route:

pages
 |    
 +-- post
 |  |  
 |  \-- [id].js

With your directory structure, the dynamic route doesn't know which file to load since index.js is resolved for a folder route such as /posts

Creating a file with the square braces will catch your /123 route as mentioned in the next.js docs: https://nextjs.org/docs/routing/dynamic-routes

The current rewrite rule you have should work for this structure where you do something like this as the rule:

{
    "source": "/post/<*>",
    "target": "/post/[id].html",
    "status": "200",
    "condition": null
}

This one worked for me:

{
    "source": "/legal/<*>",
    "target": "/legal/[pid]/index.html",
    "status": "404-200",
    "condition": null
}
Source address Target address Type Country code
/legal/<*> /legal/[pid]/index.html 404 (Rewrite) -
Related