diff --git a/src/api/ssh_keys_post.c b/src/api/ssh_keys_post.c
index e7d2a6b7a50c92004f7b459fd07061131933eb5c..5ea275b44aa4afef5b251b42c7dc68ba4075bb4a 100644
--- a/src/api/ssh_keys_post.c
+++ b/src/api/ssh_keys_post.c
@@ -19,8 +19,8 @@
 int callback_ssh_keys_post(const struct _u_request * request,
     struct _u_response * response, void * user_data)
 {
-    // Open file with append mode
-    FILE * authorized_keys = fopen(AUTHORIZED_KEYS_PATH, "a");
+    // Open file with append+read mode.
+    FILE * authorized_keys = fopen(AUTHORIZED_KEYS_PATH, "a+");
 
     // Check if that succeeded.
     if (authorized_keys == NULL)
@@ -46,8 +46,21 @@ int callback_ssh_keys_post(const struct _u_request * request,
     char * ssh_key_with_command;
     add_ssh_command(&ssh_key_with_command, ssh_key);
 
+    // Read the last character of the authorized_keys file.
+    fseek(authorized_keys, -1, SEEK_END);
+    int last_char = fgetc(authorized_keys);
+
     // Write SSH key to file
-    fprintf(authorized_keys, "%s\n", ssh_key_with_command);
+    // Check if the authorized_keys file is empty or ends in a newline.
+    if (last_char == EOF || last_char == '\n')
+    {
+        fprintf(authorized_keys, "%s\n", ssh_key_with_command);
+    }
+    else
+    {
+        // If not, prepend an extra newline.
+        fprintf(authorized_keys, "\n%s\n", ssh_key_with_command);
+    }
     fclose(authorized_keys);
     free(ssh_key_with_command);
     json_decref(json_input);